【发布时间】:2023-04-11 10:56:01
【问题描述】:
我正在尝试从字符串中删除带引号的序列。对于下面的示例,我的脚本运行良好:
import re
doc = ' Doc = "This is a quoted string: this is cool!" '
cleanr = re.compile('\".*?\"')
doc = re.sub(cleanr, '', doc)
print doc
结果(如预期):
' Doc = '
但是,当我在引用的句子中转义字符串时,我无法使用我认为正确的模式删除转义序列:
import re
doc = ' Doc = "This is a quoted string: \"this is cool!\" " '
cleanr = re.compile('\\".*?\\"') # new pattern
doc = re.sub(cleanr, '', doc)
print doc
结果
'Doc = this is cool!'
预期:
'Doc = "This is a quoted string: " '
有谁知道发生了什么?如果模式'\\".*?\\"' 是错误的,那么正确的模式是什么?
【问题讨论】:
-
当您将第一个和第二个表达式发送到
re模块时,由于失控转义,它们最终都成为相同的表达式。使用原始字符串来避免这个问题。 -
这个问题问得很好也很清楚,我真的看不出有什么理由拒绝它。