I am trying to replace a given pattern with regular expressions in Python, using re
. Here is the piece of Python code I wrote:
import re
fname = './prec.f90'
f = open(fname)
lines = f.readlines()
f.close()
for i, line in enumerate(lines):
search = re.findall('([\d*]?\.[\d*]?)+?[^dq\_]', line)
if search != []:
print('Real found in line #%d: ' %i)
print search
print('The following line:\n %s' %line)
print('will be replace by:')
newline = re.sub('([\d*]?\.[\d*]?)+?[^dq\_]', r'\g<1>d0\g<2>', line)
print('%s' %newline)
And the prec.f90
contains something like that (it is just an example, it does not means that all the strings I want to replace have the form [x]_[yz] = ...;
):
x_pr = 0.1; y_pr = 0.2; z_pr = 0.1q0
x_sp = 0.1; y_sp = 0.1d0; z_sp = 0.1q0
x_dp = 0.1; y_dp = 0.1d0; z_dp = 0.1q0
x_qp = .1; y_qp = 0.1d0; z_qp = 0.1q0
x_db = 0.; y_db = 0.1d0; y_db = 0.1q0
My goal is to modify all the pattern like 0.1
, .1
and 0.
, to get something like 0.1d0
; I don't want to modify the other patterns. The problem is that re.findall('[\d*]?\.[\d*]?)+?([^dq\_]')
matches the pattern I am looking for, but also returns an empty string for the other ones. Therefore, when I run this piece of code, it fails, being unable to replace match the first and second groups in the re.sub()
for the empty strings.
I guess one solution would be to ignore empty string in the re.sub
, or to have something like a conditional argument in it, but I could not figure out how.
Any help would be appreciated!
*
. What is the minimum string that will be on a line that you want to replace? If it is.x
then change the second\d*
to\d+
– beroe Nov 21 '14 at 18:58x.y
,.y
andx.
. I want (and need) to cover all these cases. – MBR Nov 23 '14 at 10:47