【问题标题】:How to replace multiple matches / groups with regexes?如何用正则表达式替换多个匹配项/组?
【发布时间】:2017-07-17 10:53:15
【问题描述】:

通常我们会编写以下内容来替换一个匹配项:

namesRegex = re.compile(r'(is)|(life)', re.I)
replaced = namesRegex.sub(r"butter", "There is no life in the void.")
print(replaced)

output:
There butter no butter in the void.

我想要的是用特定文本替换每个组,可能使用反向引用。即我想用“are”替换第一组(is),用“butterflies”替换第二组(life)。

也许是这样的。但以下代码无效。

namesRegex = re.compile(r'(is)|(life)', re.I)
replaced = namesRegex.sub(r"(are) (butterflies)", r"\1 \2", "There is no life in the void.")
print(replaced)

有没有办法在python的一个语句中替换多个组?

【问题讨论】:

    标签: python regex backreference


    【解决方案1】:

    您可以使用 lambda 替换,映射您要关联的关键字:

    >>> re.sub(r'(is)|(life)', lambda x: {'is': 'are', 'life': 'butterflies'}[x.group(0)], "There is no life in the void.")
    'There are no butterflies in the void.'
    

    【讨论】:

    • 如果每个模式都需要输出函数怎么办
    【解决方案2】:

    您可以先定义键和替换的映射,然后使用lambda function in replacement

    >>> repl = {'is': 'are', 'life': 'butterflies'}
    >>> print re.sub(r'is|life', lambda m: repl[m.group()], "There is no life in the void.")
    There are no butterflies in the void.
    

    我还建议您在键周围使用单词边界来保护您的搜索模式:

    >>> print re.sub(r'\b(?:is|life)\b', lambda m: repl[m.group()], "There is no life in the void.")
    There are no butterflies in the void.
    

    【讨论】:

      【解决方案3】:

      您可以使用带有搜索替换值的字典并使用简单的\w+ 正则表达式来匹配单词:

      import re
      dt = {'is' : 'are', 'life' : 'butterflies'}
      namesRegex = re.compile(r'\w+')
      replaced = namesRegex.sub(lambda m: dt[m.group()] if m.group() in dt else m.group(), "There is no life in the void.")
      print(replaced)
      

      查看Python demo

      使用这种方法,您不必担心基于交替创建太大的正则表达式模式。您可以根据要求调整模式以包含单词边界,或仅匹配字母(例如[\W\d_]+)等。重点是该模式应该匹配字典中所有作为键的搜索词。

      if m.group() in dt else m.group() 部分正在检查找到的匹配项是否作为键存在于字典中,如果不是,则返回匹配项。否则,返回字典中的值。

      【讨论】:

        【解决方案4】:

        如果您只想替换特定的单词,只需 str.replace()

        s = "There is no life in the void."
        s.replace('is', 'are').replace('life', 'butterflies')  # => 'There are no butterflies in the void.'
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-03-14
          • 2012-09-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多