How backslashes work in Python regular expressions

How does the backslash work in Python regular expressions?

According to the Python documentation, perhaps the most important metacharacter in regular expressions is the backslash. Just like in Python string literals, the backslash can be followed by various characters to represent various special sequences. It is also used to escape all metacharacters so that you can still match them in the pattern; for example, if you need to match [ or , you can precede them with a backslash to remove their special meaning: [ or .

The following code highlights the power of the backslash in Python regular expressions.

For more Python-related articles, please read: Python Tutorial

Example

import re
result = re.search('d', 'd')
print result
result = re.search(r'd', 'd')
print result.group()

Output

This will give the following output

None
d

Leave a Reply

Your email address will not be published. Required fields are marked *