jantristanmilan
jantristanmilan

Reputation: 4358

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)
print(bool(pattern.match(string)))

Upvotes: 1

Views: 1046

Answers (1)

Amadan
Amadan

Reputation: 198314

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))
print(bool(pattern.match(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.

Upvotes: 2

Related Questions