Python的string.replace正则expression式

我有一个forms的参数文件

parameter-name parameter-value 

参数可以是任何顺序,但每行只有一个参数。 我想用一个新值replace一个参数的参数值。

我使用以前发布的行replace函数( 在Python中search并replace文件中的行)来replace使用python的string.replace (pattern,subst)的行。 我正在使用的正则expression式在vim中工作,但似乎不能在string.replace中工作。 这里是我正在使用的正则expression式:

 line.replace("^.*interfaceOpDataFile.*$/i", "interfaceOpDataFile %s" % (fileIn)) 

其中interfaceOpDataFile是我要replace的参数名称(/ i不区分大小写),新参数值是fileInvariables的内容。 有没有办法让Python来识别这个正则expression式,或者有另一种方法来完成这个任务? 提前致谢。

str.replace()不识别正则expression式,使用正则expression式使用re.sub()来执行replace。

例如:

 import re line = re.sub(r"(?i)^.*interfaceOpDataFile.*$", "interfaceOpDataFile %s" % fileIn, line) 

如果在循环中这样做,最好先编译正则expression式:

 import re regex = re.compile(r"^.*interfaceOpDataFile.*$", re.IGNORECASE) for line in some_file: line = regex.sub("interfaceOpDataFile %s" % fileIn, line) # do something with the updated line 

您正在寻找re.subfunction。

 import re s = "Example String" replaced = re.sub('[ES]', 'a', s) print replaced 

将打印axample atring

re.sub绝对是你在找什么。 所以你知道,你不需要锚和通配符。

 re.sub(r"(?i)interfaceOpDataFile", "interfaceOpDataFile %s" % filein, line) 

会做同样的事情 – 匹配看起来像“interfaceOpDataFile”的第一个子string,并将其replace。

作为总结

 import sys import re f = sys.argv[1] find = sys.argv[2] replace = sys.argv[3] with open (f, "r") as myfile: s=myfile.read() ret = re.sub(find,replace, s) # <<< This is where the magic happens print ret