如前所述
@PauloBu,
r字符串前缀与regex并不特别相关,但通常与Python中的字符串有关。
普通字符串使用反斜杠字符作为特殊字符(如换行符)的转义字符:
>>> print('this is n a test')this is a test该
r前缀告诉解释不这样做:
>>> print(r'this is n a test')this is n a test>>>
这在正则表达式中很重要,因为您需要使用反斜杠将其
re完整保留到模块中-
特别是
b在单词的开头和结尾特别匹配空字符串。
re需要使用字符串
b,但是普通的字符串解释
'b'会转换为ASCII退格字符,因此您需要显式转义反斜杠(
'\b'),或者告诉python这是原始字符串(
r'b')。
>>> import re>>> re.findall('b', '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'b', 'test') # often this syntax is easier['', '']


