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

Nik*_*kos 3 python regex backreference

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

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.
Run Code Online (Sandbox Code Playgroud)

我想要的是用特定的文本替换每个组,可能使用反向引用。即我想用“ are”代替第一组(is),用“ butterfly”代替第二组(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)
Run Code Online (Sandbox Code Playgroud)

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

Uri*_*iel 5

您可以使用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.'
Run Code Online (Sandbox Code Playgroud)