I have a regex issue which do not seems as common as I thought : I would like to extract all numeric values having px units, apply some calculation, and then re-inject the new value within my string. I don't want to include the px string (see exemple below), but I could use an alternative method which keep them, or change the unit type.
Exemple, multiplying values by 2.5 :
from "2px aperture 12px science 2.1px yummy cake"
I want "5 aperture 30 science 5.25 yummy cake"
I made a sketchy script, but I don't get quite the desired output :
import re
my_string = "2px aperture 12px science 2.1px yummy cake"
nb_list= re.findall(r"([0-9.]+)px", my_string)
splitted_string = re.findall('.*?px', my_string)
print(f"splitted_string = {splitted_string}")
print(f"nb_list = {nb_list}")
new_list = []
for i in range(0, len(nb_list)):
new_n = str(float(nb_list[i])*2.5)
new_string = re.sub(r"[0-9.]+px", new_n, splitted_string[i])
new_list.append(new_string)
new_list = ''.join(new_list)
print(f"new_list = {new_list}")
Result :
new_list = 5.0 aperture 30.0 science 5.25
I understand why I get this result, but I don't know what to change to get the desired output.
Just use re.sub with a callback:
r = re.sub(
r'(\d+(\.\d+)?)px\b',
lambda m: '{:g}'.format(float(m.group(1)) * 2.5),
s)
It's easy to extend this to multiple units, for example:
units = {
'px': 2.5,
'em': 4,
}
r = re.sub(
fr'(\d+(\.\d+)?)({"|".join(units)})\b',
lambda m: '{:g}'.format(float(m.group(1)) * units[m.group(3)]),
s)
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