Supongamos que quiero cambiar the blue dog and blue cat wore blue hats
a the gray dog and gray cat wore blue hats
.¿Cómo usar la expresión regular de Python para reemplazar el uso del grupo capturado?
Con sed
pude lograr esto de la siguiente manera:
$ echo 'the blue dog and blue cat wore blue hats' | sed 's/blue \(dog\|cat\)/gray \1/g'
¿Cómo puedo hacer un reemplazo similar en Python? He intentado:
>>> 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'
La segunda respuesta es ideal, ya que coincide con la sintaxis 'sed'. –