Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use python regex to replace using captured group? [duplicate]

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' 
like image 739
Eric Wilson Avatar asked Jul 15 '11 18:07

Eric Wilson


People also ask

How do you replace groups in Python?

sub() method will replace all pattern occurrences in the target string. By setting the count=1 inside a re. sub() we can replace only the first occurrence of a pattern in the target string with another string. Set the count value to the number of replacements you want to perform.

Can you use regex in replace Python?

In this tutorial, you will learn about how to use regex (or regular expression) to do a search and replace operations on strings in Python. Regex can be used to perform various tasks in Python. It is used to do a search and replace operations, replace patterns in text, check if a string contains the specific pattern.

How do Capturing groups work in regex?

Capturing groups are a way to treat multiple characters as a single unit. They are created by placing the characters to be grouped inside a set of parentheses. For example, the regular expression (dog) creates a single group containing the letters "d" "o" and "g" .

Can I use regex in replace?

How to use RegEx with . replace in JavaScript. To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring.


1 Answers

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) 
like image 94
mac Avatar answered Oct 19 '22 05:10

mac