gpt4 book ai didi

python - pythons re.compile(r' pattern flags') 中的 "r"是什么意思?

转载 作者:IT老高 更新时间:2023-10-28 22:25:07 31 4
gpt4 key购买 nike

我正在阅读 http://docs.python.org/2/library/re.html .据此,pythons re.compile(r' pattern flags') 中的“r”指的是原始字符串表示法:

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

这样说是否公平:

re.compile(r pattern) 表示“pattern”是正则表达式,而 re.compile(pattern) 表示“pattern”是完全匹配的?

最佳答案

正如 @PauloBu 所述,r 字符串前缀与正则表达式无关,而是与 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 - pythons re.compile(r' pattern flags') 中的 "r"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21104476/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com