Problem with RE matching backslash

Peter Otten __peter__ at web.de
Tue Jan 27 16:37:54 CET 2004


Ladvánszky Károly wrote:

> What is the correct way to match/search a backslash with regular
> expressions?
> 
> print re.match('\\m', '\\m').group(0)  raises an error while
> print re.search('\\m', '\\m').group(0) yields 'm'
> 
> print re.search('\\m', '\m').group(0) yields 'm'
> print re.search('\\m', 'm').group(0) yields  'm'
> 
> Any helpful comment on this would be appreciated,

The backslash must be escaped twice: once for the Python string and once for
the regular expression:

>>> print re.match("\\\\m", "\\m").group(0)
\m

You can use raw strings to somewhat reduce the number of backslashes (but
beware of backslashes at the end of the string literals):

>>> print re.match(r"\\m", r"\m").group(0)
\m


Peter




More information about the Python-list mailing list