Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to substitute into a regular expression group in Python

Tags:

python

regex

>>> s = 'foo: "apples", bar: "oranges"'
>>> pattern = 'foo: "(.*)"'

I want to be able to substitute into the group like this:

>>> re.sub(pattern, 'pears', s, group=1)
'foo: "pears", bar: "oranges"'

Is there a nice way to do this?

like image 594
Peter Graham Avatar asked Jun 17 '10 05:06

Peter Graham


People also ask

How do you replace a regular expression in Python?

To replace a string in Python, the regex sub() method is used. It is a built-in Python method in re module that returns replaced string. Don't forget to import the re module. This method searches the pattern in the string and then replace it with a new given expression.

How do you substitute in regex?

To perform a substitution, you use the Replace method of the Regex class, instead of the Match method that we've seen in earlier articles. This method is similar to Match, except that it includes an extra string parameter to receive the replacement value.

How do you replace all occurrences of a regex pattern in a string Python?

sub() method will replace all pattern occurrences in the target string.

What is $1 in regex replace?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group. For more information about numbered capturing groups, see Grouping Constructs.


1 Answers

For me works something like:

rx = re.compile(r'(foo: ")(.*?)(".*)')
s_new = rx.sub(r'\g<1>pears\g<3>', s)
print(s_new)

Notice ?in re, so it ends with first ", also notice " in groups 1 and 3 because they must be in output.

Instead of \g<1> (or \g<number>) you can use just \1, but remember to use "raw" strings and that g<1> form is preffered because \1 could be ambiguous (look for examples in Python doc) .

like image 114
Michał Niklas Avatar answered Sep 23 '22 21:09

Michał Niklas