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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With