2
>>> match = re.search(r'\d', 'ca\d')
>>> type(match) 
<type 'NoneType'>

From my understanding 'r' means don't do any special processing with blackslashes and just return the raw string.

Also, why do i get the output below:

>>> match = re.search(r'\a', 'ca\a')
>>> match.group()
'\x07'

2 Answers 2

4

Because your input string has no digit. \d means capture a digit.

If you want to capture a literal \d, you should use \\d pattern.

See example here.

This program

import re
p = re.compile(ur'\\d')
test_str = u"ca\d"
print re.search(p, test_str).group(0)

Will output \d.

As for r'', please check this re documentation:

The solution is to use Python’s raw string notation for regular expression patterns; backslashes are not handled in any special way in a string literal prefixed with 'r'. So r"\n" is a two-character string containing '\' and 'n', while "\n" is a one-character string containing a newline. Usually patterns will be expressed in Python code using this raw string notation.

It does not mean it does not process slashes anyhow, this just lets you use a single slash instead of a doubled one. The slash is meaningful before d in a regular expression.

And as for \a, there is no such a regex metacharacter, so \ is treated as a literal.

Sign up to request clarification or add additional context in comments.

Comments

1

And in addition to stribizhev's comment, probably the 'r' (raw string indicator) is making you confused. That is used to avoid escaping. Escaping is a form of allowing writing in the code special (unprintable) characters like: TAB - ASCII 9 - "\t" CR - ASCII 13 - "\r" (Unix Enter)

But there's no special char that has the code "\d", so placing an r in front of it makes no difference, so the string will still be "\d" (2 chars) that in regex, matches over a digit.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.