How to use python regex to replace using captured group?


Suppose I want to change the blue dog and blue cat wore blue hats to the gray dog and gray cat wore blue hats.

With sed I could accomplish this as follows:

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

How can I do a similar replacement in Python? I've tried:

>>> 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'
1/9/2018 6:27:19 PM

Accepted Answer

You need to escape your backslash:

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

alternatively you can use a raw string as you already did for the regex:

p.sub(r'gray \1', s)
7/15/2011 6:31:25 PM

As I was looking for a similar answer; but wanting using named groups within the replace, I thought I'd add the code for others:

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow