我正在尝试使用Python将正则表达式替换为给定模式re
。这是我编写的Python代码:
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)
并且prec.f90
包含类似的内容(这只是一个示例,并不意味着我要替换的所有字符串都具有形式[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
我的目标是修改所有的模式0.1
,.1
并且0.
得到类似的模式0.1d0
; 我不想修改其他模式。问题是,re.findall('[\d*]?\.[\d*]?)+?([^dq\_]')
该模式与我要查找的模式匹配,但也为其他模式返回了一个空字符串。因此,当我运行这段代码时,它会失败,无法re.sub()
为空字符串替换匹配中的第一组和第二组。
我猜一种解决方案是忽略中的空字符串re.sub
,或者在其中包含类似条件参数的内容,但我不知道如何做。
任何帮助,将不胜感激!
我终于想出了按预期工作的这段代码:
import re
fname = './prec.f90'
f = open(fname)
lines = f.readlines()
f.close()
# If there was no end of the line character (\n) we would need to check if
# this is the end of the line (something like ([^dq\_0-9]|$)
regex = re.compile(r'(\d*\.\d*)([^dq\_0-9])')
for i, line in enumerate(lines):
search = regex.findall(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 = regex.sub(r'\g<1>d0\g<2>', line)
print('%s' %newline)
我第一次提出了更复杂的正则表达式([\d*]?\.[\d*]?)+?[^dq\_]
,因为别的我总是匹配任何字符串的第一部分结尾d
,q
或_
。这似乎是由于\d*
不够贪婪的事实所致。0-9
在“忽略”集中添加即可解决该问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句