Regular Expressions using Python (how to escape a backslash)

Here is a quick and dirty demo of using regular expressions in the Python programming language when backslashes are involved.

>>> string_to_match = "\\back" 

>>> print string_to_match
\back

As shown above when creating the string that will be matched, we would typically escape the backslash with a backslash so that it was taken literally.

Unfortunately this does not work so well when passed into re.compile() as a string literal.
We actually need to escape both the backslashes for this to work (so the declaration of the variable actually needed is string_to_match = “\\\\back”).

See example below of how it does not work using only two backslashes.

>>> s = "\\back"
>>> print s
\back
>>> import re
>>> c = re.compile(s)
>>> string_with_words = "\\back asdfasdf"
>>> print string_with_words
\back asdfasdf
>>> print c.match(string_with_words)
None

A cool trick is to pass the string into the re.compile() method using Python raw string notation. We do this by adding a single lower case “r” when declaring the string_to_match variable

>>> string_to_match = r"\\back"
>>> print string_to_match
\\back

See example below.

>>> s = r"\\back"
>>> print s
\\back
>>> import re
>>> c = re.compile(s)
>>> string_with_words = "\\back asdfasdf"
>>> print string_with_words
\back asdfasdf
>>> print c.match(string_with_words)
<_sre.SRE_Match object at 0x913a4b8>

Ok so to get rid of any left over confusion lets take a look at an example where we are trying to match a new line character.

>>> words = "this is the first line \n this is the second line \n"
>>> print words
this is the first line
this is the second line 

>>> s = r"\n"
>>> c = re.compile(s)
>>> print c.search(words)
<_sre.SRE_Match object at 0x8e60640>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s