【发布时间】:2018-02-04 00:42:47
【问题描述】:
我了解到“r"\n" 是一个包含'\' 和'n' 的两个字符的字符串,而"\n" 是一个包含一个换行符的一个字符的字符串。正则表达式通常会使用它在Python 代码中编写原始字符串表示法。”而r"\n" 等价于"\\n" 来表示两个字符串'\' 和'n'。
我通过打印测试它,它可以工作
>>>print(r"\n") or print("\\n")
'\n'
但是,当我在正则表达式中测试时
>>>import re
>>>re.findall("\d+", '12 cats, 10 dogs, 30 rabits, \d is here')
['12', '10', '30']
>>>re.findall(r"\d+", '12 cats, 10 dogs, 30 rabits, \d is here')
['12', '10', '30'] # Still the same as before, seems 'r' doesn't work at all
>>>re.findall("\\d+", '12 cats, 10 dogs, 30 rabits, \d is here')
['12', '10', '30'] # Doesn't work yet
当我尝试这个时,它仍然有效
>>>re.findall(r"\\d+", '12 cats, 10 dogs, 30 rabits, \d is here')
['\\d']
>>>re.findall("\\\d+", '12 cats, 10 dogs, 30 rabits, \d is here')
['\\d']
>>>re.findall("\\\\d+", '12 cats, 10 dogs, 30 rabits, \d is here')
['\\d'] # Even four backslashes
为什么?这是否意味着在使用正则表达式时我必须再添加一个反斜杠以确保它是原始字符串?
【问题讨论】:
-
"\d+"不是反斜杠具有任何非字面意义的字符串,因此无论是否使用原始语法指定它都有效。然而,对于人类读者来说,原始语法更清晰——他们不必考虑"\d"的解析方式是否不同,就像"\t"或"\n"等等。 -
原始字符串禁用 Python 的反斜杠处理。它们不会禁用正则表达式引擎的反斜杠处理;这将完全违背原始字符串的目的。