Załóżmy, że chcę zmienić the blue dog and blue cat wore blue hats
na the gray dog and gray cat wore blue hats
.Jak używać python regex do zastąpienia przy użyciu przechwyconej grupy?
Z sed
mogę tego dokonać w następujący sposób:
$ echo 'the blue dog and blue cat wore blue hats' | sed 's/blue \(dog\|cat\)/gray \1/g'
Jak mogę zrobić podobną wymianę w Pythonie? Próbowałem:
>>> 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'
Druga odpowiedź jest idealna, ponieważ pasuje do składni "sed". –