Reputation: 110163
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">'
Upvotes: 4
Views: 152
Reputation: 7353
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">'
Upvotes: 2
Reputation: 163362
You could either switch the capturing group to capture dedupMode=" and the ending "
(dedupMode=")(?:normal|accept|manual|review)(")
And replace with
\1manual\2
Or perhaps use lookarounds
(?<=dedupMode=")(?:normal|accept|manual|review)(?=")
And replace with
manual
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.
Upvotes: 3