【发布时间】: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