The Neon Prince The Neon Prince - 1 year ago 139
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)

Answer Source

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.

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