Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regex to remove substrings inside curly braces

Tags:

python

regex

I have a line which has lots of words and characters. I just want to remove the part which is included in double curly braces

{{ }}

I tried ?={{.*}} but I am not getting anything.

like image 707
Shruts_me Avatar asked May 17 '12 21:05

Shruts_me


People also ask

How do I use regular expressions to remove text in parentheses in Python?

Use re. sub() to remove text within parentheses sub(pattern, replacement, string) with pattern as the regular expression r"\([^()]*\)" and replacement as "" to remove text within parentheses in string .

How do you remove curly braces from string in Python?

To remove square brackets from the beginning and end of a string using Python, we pass “[]” to the strip() function as shown below. If you have curly brackets as well, we pass “[]{}” to strip() to remove the brackets.

Do I need to escape curly braces in regex?

To match literal curly braces, you have to escape them with \ . However, Apex Code uses \ as an escape, too, so you have to "escape the escape". You'll need to do this almost every time you want to use any sort of special characters in your regexp literally, which will happen more frequently than not.


2 Answers

Try this:

import re
s = re.sub('{{.*?}}', '', s)

Note that { and } are usually special characters in regular expressions and should usually be escaped with a backslash to get their literal meaning. However in this context they are interpreted as literals.

See it working online: ideone

like image 167
Mark Byers Avatar answered Oct 17 '22 00:10

Mark Byers


If you are trying to extract the text from inside the curly braces, try something like:

import re 
s = 'apple {{pear}} orange {banana}'
matches = re.search(r'{{(.*)}}', s)
print matches.group(1)

group(1) will contain the string 'pear'

like image 44
Beamery Avatar answered Oct 17 '22 01:10

Beamery