Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace captured groups with empty string in python

Tags:

python

regex

I currently have a string similar to the following:

str = 'abcHello Wor=A9ld'

What I want to do is find the 'abc' and '=A9' and replace these matched groups with an empty string, such that my final string is 'Hello World'.

I am currently using this regex, which is correctly finding the groups I want to replace:

r'^(abc).*?(=[A-Z0-9]+)'

I have tried to replace these groups using the following code:

clean_str = re.sub(r'^(abc).*?(=[A-Z0-9]+)', '', str)

Using the above code has resulted in:

print(clean_str)
>>> 'ld'

My question is, how can I use re.sub to replace these groups with an empty string and obtain my 'Hello World'?

like image 328
Brian Waters Avatar asked Jan 31 '23 03:01

Brian Waters


1 Answers

Capture everything else and put those groups in the replacement, like so:

re.sub(r'^abc(.*?)=[A-Z0-9]+(.*)', r'\1\2', s)
like image 142
Alex Hall Avatar answered Feb 02 '23 08:02

Alex Hall