Python re find string that may contain brackets

I am trying to find a string that may contain brackets or other characters that cannot be interpreted as simple strings.

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

I do not manage the string because it is derived from another module. My problem is that the string may contain "xyz" " , which leads to an error indicating the presence of inconsistent parentheses.

I already tried this without success

 match = re.search(r'%s' % string, text) 
+6
source share
1 answer

You can use re.escape() to avoid the line:

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

From the docs:

The returned string with all non-alphabets of the backslash; this is useful if you want to match an arbitrary literal string that can contain regular expression metacharacters in it.

+10
source

Source: https://habr.com/ru/post/954952/


All Articles