Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

re.sub for only captured group

Tags:

python

regex

Given the string:

s = '<Operation dedupeMode="normal" name="update">'

I would like to change the dedupeMode to manual. For example, the end result should be:

s = '<Operation dedupeMode="manual" name="update">'

Is there a way with re.sub to only replace the captured group and nothing else? Here is what I have so far, but it replaces everything and not just the captured group:

import re
s = '''<Operation dedupMode="normal" name="update">'''
re.sub(r'dedupMode="(normal|accept|manual|review)"', "manual", s)
# '<Operation manual name="update">'
like image 892
David542 Avatar asked Oct 24 '25 04:10

David542


2 Answers

You could either switch the capturing group to capture dedupMode=" and the ending "

(dedupMode=")(?:normal|accept|manual|review)(")

And replace with

\1manual\2

Regex demo | Python demo

Or perhaps use lookarounds

(?<=dedupMode=")(?:normal|accept|manual|review)(?=")

And replace with

manual

Regex demo | Python demo

For the options you could use a non capturing group (?:

Note that manual is also present in the alternation which might be omitted as it is the same as the replacement value.

like image 140
The fourth bird Avatar answered Oct 26 '25 18:10

The fourth bird


You could also just make a small change in your original code and that would work. Change the string to replace with:
"manual" --> 'dedupMode="manual"'

import re
s = '''<Operation dedupMode="normal" name="update">'''
re.sub(r'dedupMode="(normal|accept|manual|review)"', 'dedupMode="manual"', s)

Output:

'<Operation dedupMode="manual" name="update">'
like image 42
CypherX Avatar answered Oct 26 '25 18:10

CypherX



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!