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

时间:2011-07-15 18:25:10

标签: python regex sed replace

假设我想将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'

4 个答案:

答案 0 :(得分:53)

你需要逃避反斜杠:

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

或者你可以像正在使用正则表达式一样使用原始字符串:

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

答案 1 :(得分:16)

因为我正在寻找类似的答案;但是想要在替换中使用命名组,我想我会为其他人添加代码:

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

答案 2 :(得分:6)

试试这个:

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

答案 3 :(得分:4)

偏离主题, 对于编号的捕获组:

#/usr/bin/env python
import re

re.sub(
    pattern=r'(\d)(\w+)', 
    repl='word: \\2, digit: \\1', 
    string='1asdf'
)
  

word: asdf, digit: 1

Python使用文字反斜杠和基于1的索引进行编号的捕获组替换,如本例所示。因此\1输入为'\\1',引用第一个捕获组(\d)\2引用第二个捕获组。

相关问题