re.sub('a(b)','d','abc') yields dc, not adc.
re.sub('a(b)','d','abc')
dc
adc
Why does re.sub replace the entire capturing group, instead of just capturing group'(b)'?
re.sub
Because it's supposed to replace the whole occurrence of the pattern:
Return the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in string by the replacement repl.
If it were to replace only some subgroup, then complex regexes with several groups wouldn't work. There are several possible solutions:
re.sub('ab', 'ad', 'abc')
re.sub('(a)b', r'1d', 'abc')
repl
Match
re.sub('(?<=a)b', r'd', 'abxb')
adxb
?<=
1.4m articles
1.4m replys
5 comments
57.0k users