【问题标题】:Replacing words in a string, ignoring quotation marks [duplicate]替换字符串中的单词,忽略引号[重复]
【发布时间】:2014-08-05 19:35:55
【问题描述】:

我正在检查一个文本字符串,我希望更改文本中的某些单词,忽略引号内的任何内容。

示例:如果我想将“my”替换为“MY”

Hello my name is "Tom, and my favourite sport is football"

会变成

Hello MY name is "Tom, and my favourite sport is football"

我正在使用正则表达式来搜索要替换的单词。

我正在用 Python 编写这个脚本。

编辑:我将在原始文本中搜索列表中的单词,而不是文字单词。匹配“整个单词”也很重要。

【问题讨论】:

  • 您在使用正则表达式时遇到困难还是刚刚开始?
  • “我正在使用正则表达式搜索要替换的单词” 看来你已经有了,可以分享一下吗?
  • 会不会有转义引号,只担心双引号?
  • 我没有使用正则表达式搜索我想要替换的单词的问题。我不知道如何替换其他实例。
  • @sweeneyrod 只担心双引号

标签: python regex string file-io


【解决方案1】:

你可以使用这个正则表达式:

(\bmy\b)(?=(?:[^"]|"[^"]*")*$)

Demo

Python 演示:

>>> txt='''\
... Hello my name is "Tom, and my favourite sport is football" my O my
... Hello Tom, my name is Bonney
... not mymymy'''
>>> tgt='my'
>>> print re.sub(r'(\b%s\b)(?=(?:[^"]|"[^"]*")*$)' % tgt, tgt.upper(), txt)
Hello MY name is "Tom, and my favourite sport is football" MY O MY
Hello Tom, MY name is Bonney
not mymymy

【讨论】:

  • 这导致了演示中的错误,并且引号内的字符串仍然匹配
  • 哪个demo出现什么错误?
猜你喜欢
  • 2020-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-06
  • 2017-12-20
  • 2012-07-14
  • 1970-01-01
  • 2019-05-26
相关资源
最近更新 更多