Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
575 views
in Technique[技术] by (71.8m points)

regex - What does the "r" in pythons re.compile(r' pattern flags') mean?

I am reading through http://docs.python.org/2/library/re.html. According to this the "r" in pythons re.compile(r' pattern flags') refers the raw string notation :

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" " is a two-character string containing '' and 'n', while " " is a one-character string containing a newline. Usually patterns will be expressed in Python code using this raw string notation.

Would it be fair to say then that:

re.compile(r pattern) means that "pattern" is a regex while, re.compile(pattern) means that "pattern" is an exact match?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As @PauloBu stated, the r string prefix is not specifically related to regex's, but to strings generally in Python.

Normal strings use the backslash character as an escape character for special characters (like newlines):

>>> print('this is 
 a test')
this is 
 a test

The r prefix tells the interpreter not to do this:

>>> print(r'this is 
 a test')
this is 
 a test
>>> 

This is important in regular expressions, as you need the backslash to make it to the re module intact - in particular, matches empty string specifically at the start and end of a word. re expects the string , however normal string interpretation '' is converted to the ASCII backspace character, so you need to either explicitly escape the backslash ('\b'), or tell python it is a raw string (r'').

>>> import re
>>> re.findall('', 'test') # the backslash gets consumed by the python string interpreter
[]
>>> re.findall('\b', 'test') # backslash is explicitly escaped and is passed through to re module
['', '']
>>> re.findall(r'', 'test') # often this syntax is easier
['', '']

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...