pythons re.compile(r'pattern flags')中的“r”是什么意思?

2024-05-14 06:18:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在通读http://docs.python.org/2/library/re.html。根据这一点,pythons re.compile(r模式标志)中的“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(rpattern)表示“pattern”是正则表达式,而re.compile(pattern)表示“pattern”是完全匹配的?


Tags: inorgrehttpdocsstringrawis
3条回答

@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
['', '']

不,因为粘贴的文档解释了字符串的前缀r表示字符串是^{}.

由于字符的Python转义和regex转义(都使用反斜杠\字符)之间的冲突,原始字符串提供了一种向Python指示您想要未转义字符串的方法。

检查以下各项:

>>> "\n"
'\n'
>>> r"\n"
'\\n'
>>> print "\n"


>>> print r"\n"
\n

前缀为r只表示字符串应该按字面意思处理反斜杠\,而不是python的转义字符。

例如,在搜索单词boundry时,这很有帮助。它的regex是\b,但是要在Python字符串中捕获它,我需要使用"\\b"作为模式。相反,我可以使用原始字符串:r"\b"进行模式匹配。

当试图在regex中找到一个文本反斜杠时,这变得特别方便。要匹配regex中的反斜杠,我需要使用模式\\,要在python中转义它,意味着我需要转义每个斜杠,然后模式变成"\\\\",或者更简单的r"\\"

正如您在更长更复杂的正则表达式中所猜测的那样,额外的斜杠可能会让人混淆,因此原始字符串通常被认为是解决问题的方法。

不。不是所有regex语法都需要前面加上\,所以.*+等在模式中仍然有特殊的含义

经常使用r''作为regex的便利,因为它可以防止将\加倍的混乱

相关问题 更多 >