【发布时间】:2019-10-24 16:27:16
【问题描述】:
我不明白 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
这让我更加困惑。
注意: 我阅读了关于原始字符串的this 堆栈溢出问题,该问题非常完整。尽管如此,它并没有谈到替换
【问题讨论】:
-
它没有“谈论”替换,因为替换模式不是正则表达式。
'\.'=r'\.',它是\和.字符组合。由于它是一个替换模式,因此您可以在结果中得到该文本。但是,您在测试中使用了\,它甚至更加棘手:它在正则表达式替换模式中是 special 的。re.sub(r'\s+\.', r'\\.', text)将产生与text2和text3相同的字符串。见this Python demo。
标签: python regex substitution backslash rawstring