The Neon Prince The Neon Prince - 4 months ago 94
Python Question

Regular expression won't match special character in Python

I do not understand why the following code snippet returns false. I understand that special characters must be escaped, but re.escape() already does that.

import re

string = re.escape('$')
pattern = re.compile(string)


You are escaping the wrong one. The string to be searched does not need to be modified. But strings you include in the pattern to be matched literally do.

import re

string = '$'
pattern = re.compile(re.escape(string))

Here, pattern \$ (match literal $) is matched against the string "$", and succeeds.

In your example, the pattern \$ (match literal $) is matched against the string "\$" (r"\$" or "\\$" in Python), and fails because match requires the pattern to cover the entire string, and the backslash is left unmatched.