Python的单引号、双引号或三引号’;正则表达式的原始字符串符号?
我想知道什么时候用Python的原始字符串表示法来表示正则表达式:单引号、双引号还是三双引号 从 当与三重引号字符串一起使用时,这使REs的格式更为整洁:Python的单引号、双引号或三引号’;正则表达式的原始字符串符号?,python,regex,Python,Regex,我想知道什么时候用Python的原始字符串表示法来表示正则表达式:单引号、双引号还是三双引号 从 当与三重引号字符串一起使用时,这使REs的格式更为整洁: pat = re.compile(r""" \s* # Skip leading whitespace (?P<header>[^:]+) # Header name \s* : # Whitespace, and a colon (?P<value&g
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"\d"
如果没有r
,字符串将无法以您期望的状态到达引擎。你必须避开反斜杠
三重报价的好处
使用三重引号(正如其他人所说)是指字符串可以跨越多行,如:
r"""(?x) # let's write this complex regex in free-space mode!
\d # match a digit
$ # at the end of a line
"""
三重引号示例演示了详细模式,其中从正则表达式中剥离空白,您可以使用空白来提高可读性。奇怪的是,这个例子没有提到关于verbose的另一部分:它忽略了从#到行尾的所有注释。因为三重引号保留了换行符,所以regex会看到多行在其末尾有注释
>>> 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
...
>>>
打印(r)
…\s*#跳过前导空格
…(?P[^:]+)#标题名称
…\s*:#空格和冒号
... ...
... """)
\s*#跳过前导空格
(?P[^:]+)#标题名称
\s*:#空格和冒号
...
>>>
如果您只是使用一组单引号来连接字符串,那么它只会看到一行带有很长注释的内容
>>> 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...
>>>
>>打印(
…r“\s*#跳过前导空格”
…r“(?P[^::]+)#标题名称”
…r“\s*:#空格和冒号”
…r“…”)
\s*#跳过前导空格(?P[^::]+)#标题名\s*:#空格和冒号。。。
>>>
您可以将\n添加到每个字符串的末尾,以返回到多行字符串
至于单韵诗双引号,这只是个人偏好,对python或正则表达式来说并不重要。如果引用的字符串包含“,then”便于引用,反之亦然。这里没有特定于正则表达式的内容。1) 双引号和单引号是等价的。2) 三重引号用于多行字符串文字。原始字符串也是如此。三重撇号和三重引号是多行字符串。@JanneKarila Gosh,这太尴尬了,谢谢你指出这一点!
>>> 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...
>>>