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">'
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.
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">'
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