Python string.replace 正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16720541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python string.replace regular expression
提问by Troy Rockwood
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-valuewith a new value.
参数可以按任何顺序排列,但每行只有一个参数。我想parameter-value用新值替换一个参数。
I am using a line replace function posted previouslyto replace the line which uses Python's 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().
我正在使用之前发布的行替换函数来替换使用 Python 的string.replace(pattern, sub). 例如,我使用的正则表达式在 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 fileInvariable.
"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 识别这个正则表达式,或者还有另一种方法来完成这个任务?
采纳答案by Andrew Clark
str.replace()v2|v3does not recognize regular expressions.
To perform a substitution using a regular expression, use re.sub()v2|v3.
要使用正则表达式执行替换,请使用re.sub()v2| 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
回答by Jacek Przemieniecki
回答by Nelz11
re.subis definitely what you are looking for. And so you know, you don't need the anchors and the wildcards.
re.sub绝对是您要找的。所以你知道,你不需要锚点和通配符。
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”的子字符串并替换它。
回答by kpie
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

