【问题标题】:How remove escaped sequences (e.g. \"escaped string\") using regex?如何使用正则表达式删除转义序列(例如“转义字符串”)?
【发布时间】: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 模块时,由于失控转义,它们最终都成为相同的表达式。使用原始字符串来避免这个问题。
  • 这个问题问得很好也很清楚,我真的看不出有什么理由拒绝它。

标签: python regex string match


【解决方案1】:

doc 不包含任何转义字符,因此您的正则表达式不匹配。

在字符串中添加r前缀,这意味着它应该被视为一个原始字符串,忽略转义代码。

试试这个:

>>> doc = r' Doc = "This is a quoted string: \"this is cool!\" " '
>>> cleanr = re.compile(r'\\".*?\\"')
>>> re.sub(cleanr, '', doc)
' Doc = "This is a quoted string:  " '

【讨论】:

  • 谢谢你们的及时回答。效果很好。
  • 请注意,此答案假定您能够将 doc 定义为代码中的文字。如果你能做到这一点,那就太好了。如果您是从其他来源获取的,最好希望它包含文字反斜杠。
猜你喜欢
  • 2010-09-21
  • 1970-01-01
相关资源
最近更新 更多