如何使用python正则表达式替换使用捕获的组?

2024-09-28 21:42:50 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我想将the blue dog and blue cat wore blue hats更改为the gray dog and gray cat wore blue hats

有了sed我可以做到如下:

$ echo 'the blue dog and blue cat wore blue hats' | sed 's/blue \(dog\|cat\)/gray \1/g'

如何在Python中进行类似的替换?我试过:

>>> import re
>>> s = "the blue dog and blue cat wore blue hats"
>>> p = re.compile(r"blue (dog|cat)")
>>> p.sub('gray \1',s)
'the gray \x01 and gray \x01 wore blue hats'

Tags: andtheimportechorebluesedcat
3条回答

你需要避开你的反斜杠:

p.sub('gray \\1', s)

或者,也可以像对regex所做的那样使用原始字符串:

p.sub(r'gray \1', s)

我在寻找一个类似的答案;但是想要在replace中使用命名组,我想我应该为其他人添加代码:

p = re.compile(r'blue (?P<animal>dog|cat)')
p.sub(r'gray \g<animal>',s)

试试这个:

p.sub('gray \g<1>',s)

相关问题 更多 >