David542
David542

Reputation: 110163

re.sub for only captured group

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

Answers (2)

CypherX
CypherX

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

The fourth bird
The fourth bird

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

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.

Upvotes: 3

Related Questions