如何用正则表达式替换多个匹配项/组?

How to replace multiple matches / groups with regexes?

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

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" ", "There is no life in the void.")
print(replaced)

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

您可以先定义键和替换映射,然后使用 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.

您可以使用 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.'

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

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

您可以使用带有搜索替换值的字典并使用简单的 \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() 部分正在检查找到的匹配项是否作为字典中的键存在,如果不是,则 returns 返回匹配项。否则,返回字典中的值。