I have a regex
(obligor_id): (\d+);(obligor_id): (\d+):
A sample match like below:
Match 1
Full match 57-95 `obligor_id: 505732;obligor_id: 505732:`
Group 1. 57-67 `obligor_id`
Group 2. 69-75 `505732`
Group 3. 76-86 `obligor_id`
Group 4. 88-94 `505732`
I am trying to partially replace the full match to the following:
obligor_id: 505732;obligor_id: 505732: -> obligor_id: 505732;
Two ways to achieve so,
replace group 3 and 4 with empty string
replace group 1 and 2 with empty string, and then replace group 4 to (\d+);
How can I achieve these 2 in python? I know there is a re.sub function, but I only know how to replace the whole, not partially replace group.
Thanks in advance.
You can change capturing groups and reference them in the substitution string:
s = 'obligor_id: 505732;obligor_id: 505732:'
re.sub(r'(obligor_id: \d+;)(obligor_id: \d+:)', r'\1', s)
# => 'obligor_id: 505732;
Thanks for answers and advices:
I achieved them as below for future users:
re.sub(regex, r'\1: \2;', str)
re.sub(regex, r'\3: \4;', str)
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