Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace partial groups in python regex?

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,

  1. replace group 3 and 4 with empty string

  2. 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.

like image 228
Pythoner Avatar asked Oct 31 '25 00:10

Pythoner


2 Answers

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;
like image 96
mrzasa Avatar answered Nov 01 '25 18:11

mrzasa


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)
like image 42
Pythoner Avatar answered Nov 01 '25 19:11

Pythoner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!