I have a snippet that finds floating point numbers like 1.321234123. I would like to get rid of some precision and make 1.3212 out of it. But how can i access the found match, convert it and replace it?
Python Source:
import fileinput
import re
myfile = open("inputRegex.txt", "r")
for line in myfile:
line = re.sub(r"[+-]? *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?", "foundValue", line.rstrip())
print(line)
The Input File:
4.2abc -4.5 abc - 1.321234123 abc + .1e10 abc . abc 1.01e-2 abc
1.01e-.2 abc 123 abc .123
Use fileinput.FileInput
, with inplace=True
. printed line will be used as a replacement string for each line.
myfile = fileinput.FileInput("inputRegex.txt", inplace=True)
for line in myfile:
line = re.sub(r"[+-]? *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?",
"foundValue",
line.rstrip())
print(line)
UPDATE
re.sub
can accept a function as replacement. It will be called with match object and the return value of the function is used as a replacement string.
The following is slightly modified version to use captured groups (to use in replacement function).
line = re.sub(r"([+-]? *)(\d+(?:\.\d*)?|\.\d+)([eE][+-]?\d+)?",
lambda m: m.group(1) + re.sub('(\..{4}).*', r'\1', m.group(2)) + (m.group(3) or ''),
line.rstrip())
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