[Tutor] Regex/Raw String confusion
Alan Gauld
alan.gauld at yahoo.co.uk
Thu Aug 4 04:27:34 EDT 2016
On 04/08/16 02:54, Jim Byrnes wrote:
> Is the second example a special case?
>
> phoneNumRegex = re.compile(r'(\(\d\d\d\)) (\d\d\d-\d\d\d\d)')
>
> I ask because it produces the same results with or without the ' r '.
That's because in this specific case there are no conflicts between
the regex escape codes and the Python escape codes. In other
words Python does not treat '\(' or '\d' as special characters
so it doesn't change the string passed to the regex.
(It would be a different story if you had used, say, a
'\x' or '\n' or '\b' in the regex.)
In general you should proceed with caution and assume that
there might be a Python escape sequence lurking in the regex
and use raw just in case.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list