本文翻译自:Python string.replace regular expression [duplicate]
This question already has an answer here: 这个问题在这里已有答案:
I have a parameter file of the form: 我有一个表格的参数文件:
parameter-name parameter-value
Where the parameters may be in any order but there is only one parameter per line. 参数可以按任何顺序排列,但每行只有一个参数。 I want to replace one parameter's parameter-value
with a new value. 我想用一个新值替换一个参数的parameter-value
值。
I am using a line replace function posted previously to replace the line which uses Python's string.replace(pattern, sub)
. 我使用之前发布的行替换函数来替换使用Python的string.replace(pattern, sub)
。 The regular expression that I'm using works for instance in vim but doesn't appear to work in string.replace()
. 我正在使用的正则表达式在vim中工作,但似乎不能在string.replace()
。
Here is the regular expression that I'm using: 这是我正在使用的正则表达式:
line.replace("^.*interfaceOpDataFile.*$/i", "interfaceOpDataFile %s" % (fileIn))
Where "interfaceOpDataFile"
is the parameter name that I'm replacing (/i for case-insensitive) and the new parameter value is the contents of the fileIn
variable. 其中"interfaceOpDataFile"
是我要替换的参数名称(/ i表示不区分大小写),新参数值是fileIn
变量的内容。
Is there a way to get Python to recognize this regular expression or else is there another way to accomplish this task? 有没有办法让Python识别这个正则表达式,否则还有另一种方法可以完成这个任务吗?
#1楼
参考:https://stackoom.com/question/189m9/Python-string-replace正则表达式-复制
#2楼
str.replace()
v2 | str.replace()
v2 | v3 does not recognize regular expressions. v3无法识别正则表达式。
To perform a substitution using a regular expression, use re.sub()
v2 | 要使用正则表达式执行替换,请使用re.sub()
v2 | v3 . v3 。
For example: 例如:
import re
line = re.sub(
r"(?i)^.*interfaceOpDataFile.*$",
"interfaceOpDataFile %s" % fileIn,
line
)
In a loop, it would be better to compile the regular expression first: 在循环中,最好先编译正则表达式:
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
#3楼
You are looking for the re.sub function. 您正在寻找re.sub功能。
import re
s = "Example String"
replaced = re.sub('[ES]', 'a', s)
print replaced
will print axample atring
将打印axample atring
#4楼
re.sub
is definitely what you are looking for. re.sub
绝对是你要找的。 And so you know, you don't need the anchors and the wildcards. 所以你知道,你不需要锚和通配符。
re.sub(r"(?i)interfaceOpDataFile", "interfaceOpDataFile %s" % filein, line)
will do the same thing--matching the first substring that looks like "interfaceOpDataFile" and replacing it. 将做同样的事情 - 匹配看起来像“interfaceOpDataFile”的第一个子串并替换它。
#5楼
As a summary 作为总结
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