Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regex find and replace inplace

Tags:

python

regex

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
like image 375
user1767754 Avatar asked Dec 16 '15 01:12

user1767754


1 Answers

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())
like image 155
falsetru Avatar answered Oct 20 '22 01:10

falsetru