[Tutor] Regex/Raw String confusion
David Rock
david at graniteweb.com
Thu Aug 4 00:29:36 EDT 2016
> On Aug 3, 2016, at 20:54, Jim Byrnes <jf_byrnes at comcast.net> wrote:
>
> Is the second example a special case?
>
> phoneNumRegex = re.compile(r'(\(\d\d\d\)) (\d\d\d-\d\d\d\d)')
> mo = phoneNumRegex.search('My phone number is: (415) 555-4242.')
> print(mo.group(1))
> print()
> print(mo.group(2))
>
> I ask because it produces the same results with or without the ' r '.
No, it’s not a special case. The backslashes in this case are a way to simplify what could otherwise be very unwieldy. There are several of these character groups (called special sequences in the documentation). For example, \s means any whitespace character, \w means any alphanumeric or underscore, \d means any digit, etc.
You can look them up in the docs:
https://docs.python.org/2/library/re.html
—
David Rock
david at graniteweb.com
More information about the Tutor
mailing list