A noob question. I was reading a documentation on use of regexes in python. I was under the impression that using a raw string would treat '\' as it is and not consider whatever is following it as an escape sequence. In the example I was reading, however,
>>> phoneNumRegex = re.compile(r'(\(\d\d\d\)) (\d\d\d-\d\d\d\d)')
>>> mo = phoneNumRegex.search('My phone number is (415) 555-4242.')
>>> mo.group(1)
'(415)'
>>> mo.group(2)
'555-4242'
Clearly, the author has escaped '(' with '\' . I want to understand how. I thought putting a 'r' at the bring would treat '\' no differently.
Yes, this code escapes the '(' for the purposes of defining the regex, but the Python interpreter retains the '\' in the string.
Without defining this using the raw string literal form, you would have had to write:
phoneNumRegex = re.compile('(\\(\\d\\d\\d\\)) (\\d\\d\\d-\\d\\d\\d\\d)')
The \ in a raw string literal is a literal \, just what we need to use to escape shorthand character classes and special regex characters with.
The ( is a beginning of a grouping construct and there must be a closing unescaped ). These (...) are never part of the match. The \( and \) are literal ( and ) and these are part of the match.
Think of a regex engine as a customer who is delivered a string. Re requires \d. When you use "\d", Python thinks it is an escape sequence like \n, but it is not, so it retains the \ since this is default behavior for unknown escape sequence and gives \d to the re engine. When you write r"\d" Python knows that \ is a literal \ and will readily provide \d to the re engine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With