我不明白 python 正则表达式中的 scape 运算符 \ 以及原始字符串的 r' 的功能逻辑。一些帮助表示赞赏。
代码:
import re
text=' esto .es 10 . er - 12 .23 with [ and.Other ] here is more ; puntuation'
print('text0=',text)
text1 = re.sub(r'(\s+)([;:\.\-])', r'\2', text)
text2 = re.sub(r'\s+\.', '\.', text)
text3 = re.sub(r'\s+\.', r'\.', text)
print('text1=',text1)
print('text2=',text2)
print('text3=',text3)
该理论说:反斜杠字符('\')表示特殊形式或允许使用特殊字符而不调用它们的特殊含义。
并且就本问题末尾提供的链接解释而言,r' 表示原始字符串,即符号没有特殊含义,它保持不变。
所以在上面的正则表达式中,我希望 text2 和 text3 是不同的,因为替换文本是 '.' 在文本 2 中,即一个句点,而(原则上)文本 3 中的替换文本是 r'。这是一个原始字符串,即应该出现的字符串、反斜杠和句点。但它们的结果是一样的:
结果是:
text0= esto .es 10 . er - 12 .23 with [ and.Other ] here is more ; puntuation
text1= esto.es 10. er- 12.23 with [ and.Other ] here is more; puntuation
text2= esto\.es 10\. er - 12\.23 with [ and.Other ] here is more ; puntuation
text3= esto\.es 10\. er - 12\.23 with [ and.Other ] here is more ; puntuation
#text2=text3 but substitutions are not the same r'\.' vs '\.'
在我看来,r' 在替换部分和反斜杠中的工作方式不同。另一方面,我的直觉告诉我我在这里遗漏了一些东西。
编辑 1:遵循@Wiktor Stribiżew 评论。他指出(按照他的链接):
import re
print(re.sub(r'(.)(.)(.)(.)(.)(.)', 'a\6b', '123456'))
print(re.sub(r'(.)(.)(.)(.)(.)(.)', r'a\6b', '123456'))
# in my example the substitutions were not the same and the result were equal
# here indeed r' changes the results
这使:
ab
a6b
这让我更加困惑。
注意:我阅读了这个关于原始字符串的堆栈溢出问题,它非常完整。尽管如此,它并没有谈到替代品