shan shan - 3 years ago 117
Python Question

Using regex with special characters to find a match in python

I am extracting a string and need to check whether it follows a particular pattern


<![any word]>



if so I need to replace it with "". I am trying the following code

string1 = "<![if support]> hello"
string = re.sub(re.compile("<![.*?]>"),"",string1)
print(string)


But I am getting the output as

<![if support]> hello


I wish to get the output as hello. What am I doing wrong here?

Answer Source

[ and ] are treated as meta characters in regex. You'll need to escape them:

In [1]: re.sub(re.compile("<!\[.*?\]>"),"", "<![if support]> hello")
Out[1]: ' hello'

As a simplification (courtesy Wiktor Stribiżew), you can escape just the first left paren, shortening your regex to "<!\[.*?]>".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download