【发布时间】:2012-10-25 23:53:15
【问题描述】:
可能重复:
What exactly do “u” and “r”string flags in Python, and what are raw string litterals?
p = re.compile(r'(\b\w+)\s+\1')
p.search('Paris in the the spring').group()
第一行r是什么意思?
【问题讨论】:
可能重复:
What exactly do “u” and “r”string flags in Python, and what are raw string litterals?
p = re.compile(r'(\b\w+)\s+\1')
p.search('Paris in the the spring').group()
第一行r是什么意思?
【问题讨论】:
r 指定 Python 中的原始字符串,其规则与标准字符串不同,例如您不必转义反斜杠和其他特殊字符。
【讨论】:
\w 没有任何意义。 docs.python.org/2/reference/…
r"\w" 将匹配任何字母数字字符。使用 r 可以输入 r"\w" 而不是 "//w"。 r 允许您在字符串中包含 Python 转义序列,而无需转义 \。我觉得我对你不太清楚。
解决方案是对正则表达式模式使用 Python 的原始字符串表示法;在以 'r' 为前缀的字符串文字中,不会以任何特殊方式处理反斜杠。所以 r"\n" 是一个包含 '\' 和 'n' 的两个字符的字符串,而 "\n" 是一个包含换行符的一个字符的字符串。通常模式将使用这种原始字符串表示法在 Python 代码中表示。
【讨论】:
\w 不是转义序列,它是一个特殊序列(在re 文档的syntax section 底部)。