Python 原始字符串表示法中应使用单引号、双引号还是三重引号用于正则表达式?
我想知道在Python的原始字符串表示法中,什么时候使用单引号、双引号或三重双引号来写正则表达式?
来源于 https://docs.python.org/2/howto/regex.html
使用三重引号的字符串时,可以让正则表达式的格式看起来更整齐:
pat = re.compile(r""" \s* # Skip leading whitespace (?P<header>[^:]+) # Header name \s* : # Whitespace, and a colon (?P<value>.*?) # The header's value -- *? used to # lose the following trailing whitespace \s*$ # Trailing whitespace to end-of-line """, re.VERBOSE)
我把三重双引号换成了双引号和单引号,但都不行。
不过,文章中在其他例子里也用到了单引号和双引号:
r"\w+\s+\1"
r'(\b\w+)\s+\1'
我想知道这是为什么?
谢谢!
2 个回答
1
这个三重引号的例子展示了“详细模式”,在这种模式下,正则表达式中的空格会被去掉,你可以利用这些空格来提高可读性。奇怪的是,这个例子没有提到详细模式的另一个部分:它会把每行中#后面的内容当作注释忽略掉。因为三重引号保留了换行符,所以正则表达式会看到多行,其中每行的末尾都有注释。
>>> print (r"""
... \s* # Skip leading whitespace
... (?P<header>[^:]+) # Header name
... \s* : # Whitespace, and a colon
... ...
... """)
\s* # Skip leading whitespace
(?P<header>[^:]+) # Header name
\s* : # Whitespace, and a colon
...
>>>
如果你只是用一堆单引号把字符串连接起来,正则表达式只会看到一行,后面跟着一个很长的注释。
>>> print (
... r" \s* # Skip leading whitespace"
... r" (?P<header>[^:]+) # Header name"
... r" \s* : # Whitespace, and a colon"
... r"...")
\s* # Skip leading whitespace (?P<header>[^:]+) # Header name \s* : # Whitespace, and a colon...
>>>
你可以在每个字符串的末尾加上\n,这样就能恢复成多行字符串了。
至于单引号和双引号的选择,这完全是个人喜好,对Python或正则表达式没有影响。如果引号中的字符串包含了",那么用'来引用会比较方便,反之亦然,就这样。
7
原始字符串的好处
使用原始字符串时,你不需要担心字符串内部的反斜杠,比如在:
r"\d"
如果没有加 r
,字符串就不会以你期望的状态传递给引擎。你需要对反斜杠进行转义。
三重引号的好处
使用三重引号(正如其他人所说的)可以让你的字符串跨越多行,比如:
r"""(?x) # let's write this complex regex in free-space mode!
\d # match a digit
$ # at the end of a line
"""