Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python re find string that may contain brackets

I am trying to search for a string that may contain brackets or other characters that may not be interpreted as plain strings.

def findstring(string, text):
    match = re.search(string, text)

I do not control the string as it is derived from another module. My problem is that the string may contain "xyz)", which raises an error telling me that there are unmatched brackets.

I already tried this without success

match = re.search(r'%s' % string, text)
like image 728
JohnGalt Avatar asked Sep 30 '13 15:09

JohnGalt


1 Answers

You can use re.escape() to escape the string:

match = re.search(re.escape(string), text)

From docs:

Return string with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it.

like image 106
Rohit Jain Avatar answered Nov 09 '22 07:11

Rohit Jain