Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace part of string using a regular expression

Tags:

python

regex

s = 'scores:start:4.2.1.3.4.3:final:55.34.13.63.44.34'

I'm trying to reset the start scores to 0.0.0.0.0.0 so that it reads

scores:start:0.0.0.0.0.0:final:55.34.13.63.44.34

This works:

re.sub('start\:(\d+\.\d+\.\d+\.\d+\.\d+\.\d+)','0.0.0.0.0.0',s)

But I was looking for something more flexible to use in case the amount of scores change.

EDIT: Actually my example does not work, because start is removed from the string

scores:0.0.0.0.0.0:final:55.34.13.63.44.34

but I would like to keep it:

scores:start:0.0.0.0.0.0:final:55.34.13.63.44.34
like image 884
HappyPy Avatar asked Jul 22 '26 10:07

HappyPy


1 Answers

You may use this re.sub with a lambda if you want to replace dot seperated numbers with same number of zeroes:

>>> import re
>>> s = 'scores:start:4.2.1.3.4.3:final:55.34.13.63.44.34'
>>> re.sub(r'start:\d+(?:\.\d+)+', lambda m: re.sub(r'\d+', '0', m.group()), s)
'scores:start:0.0.0.0.0.0:final:55.34.13.63.44.34'

We are using regex as start:\d+(?:\.\d+)+ to match text that starts with start: and followed by digits separated by dot.

In lambda part we replace each 1+ digit with 0 to get same number of zeroes in output as the input.

like image 114
anubhava Avatar answered Jul 24 '26 22:07

anubhava



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!