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

2024-05-19

通常我们会编写以下内容来替换一场比赛:

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中的一个语句中替换多个组?


您可以使用 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.'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何用正则表达式替换多个匹配/组? 的相关文章

随机推荐