我不太理解Python正则表达式中原始字符串r'和转义运算符\共同使用的逻辑。希望能得到一些帮助。
代码如下:
理论上说: 反斜杠字符('\')用于表示特殊形式或允许使用特殊字符而不调用其特殊含义。
至于本问题末尾提供的链接所解释的,r'代表原始字符串,即符号没有特殊含义,就是它本身。
因此,在上面的正则表达式中,我期望text2和text3是不同的,因为在text2中替换文本为“.”,即一个句点,而(原则上)text3中的替换文本为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是不同的,因为在text2中替换文本为“.”,即一个句点,而(原则上)text3中的替换文本为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
这更让我感到困惑。
注意: 我阅读了关于原始字符串的这篇Stack Overflow问题,它非常完整。然而,它没有涉及到替换。
'\.'
=r'\.'
,它是一个\
和.
字符的组合。由于它是一个替换模式,所以你会在结果中得到这个文本。然而,在你的测试中使用\
,这更加棘手:在正则表达式替换模式中,它是特殊的。re.sub(r'\s+\.', r'\\.', text)
将产生与text2
和text3
相同的字符串。请参见此Python演示。 - Wiktor Stribiżew