498

我有一个形式的参数文件:

parameter-name parameter-value

其中参数可以按任何顺序排列,但每行只有一个参数。我想parameter-value用一个新值替换一个参数。

我正在使用之前发布的行替换功能来替换使用 Python 的string.replace(pattern, sub). 我正在使用的正则表达式例如在 vim 中有效,但似乎在string.replace().

这是我正在使用的正则表达式:

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

我要替换的参数名称在哪里"interfaceOpDataFile"(/i 表示不区分大小写),新参数值是fileIn变量的内容。

有没有办法让 Python 识别这个正则表达式,或者有没有另一种方法来完成这个任务?

4

4 回答 4

659

str.replace() v2 | v3不识别正则表达式。

要使用正则表达式执行替换,请使用re.sub() v2 | v3

例如:

import re

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

在循环中,最好先编译正则表达式:

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
于 2013-05-23T17:53:28.327 回答
474

您正在寻找re.sub功能。

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

将打印axample atring

于 2013-05-23T17:55:49.897 回答
18

作为总结

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
于 2014-12-06T19:10:00.600 回答
11

re.sub绝对是您正在寻找的。所以你知道,你不需要锚点和通配符。

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

会做同样的事情——匹配第一个看起来像“interfaceOpDataFile”的子字符串并替换它。

于 2013-05-23T18:10:17.830 回答