Python string.replace 正则表达式 [英] Python string.replace regular expression
问题描述
我有一个如下形式的参数文件:
I have a parameter file of the form:
parameter-name parameter-value
参数可以按任何顺序排列,但每行只有一个参数.我想用一个新值替换一个参数的 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.
我正在使用行替换功能 之前发布 替换使用 Python 的 string.replace(pattern, sub)
.例如,我使用的正则表达式在 vim 中有效,但在 string.replace()
中似乎不起作用.
I am using a line replace function posted previously to 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()
.
这是我使用的正则表达式:
Here is the regular expression that I'm using:
line.replace("^.*interfaceOpDataFile.*$/i", "interfaceOpDataFile %s" % (fileIn))
其中 "interfaceOpDataFile"
是我要替换的参数名称(/i 表示不区分大小写),新参数值是 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.
有没有办法让 Python 识别这个正则表达式,或者还有其他方法来完成这个任务?
Is there a way to get Python to recognize this regular expression or else is there another way to accomplish this task?
推荐答案
str.replace()
v2|v3 does not recognize regular expressions.
要使用正则表达式执行替换,请使用 re.sub()
v2|v3.
To perform a substitution using a regular expression, use re.sub()
v2|v3.
例如:
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
这篇关于Python string.replace 正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!