>>> 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?
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.
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.
sub() method will replace all pattern occurrences in the target string.
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.
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) .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With