您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python re.compile(r'模式标志')中的“ r”是什么意思?

python re.compile(r'模式标志')中的“ r”是什么意思?

如前所述@PauloBur字符串前缀与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
['', '']
python 2022/1/1 18:31:52 有199人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶