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

问题描述 投票:3回答:4

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

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),用“ 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)

是否有一种方法可以在python中的一个语句中替换多个组?

python regex backreference
4个回答
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.'

3
投票

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

2
投票

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


0
投票

如果您只想替换特定的单词,则不要超过str.replace()

str.replace()
© www.soinside.com 2019 - 2024. All rights reserved.