Tro*_*ood 379 python regex replace
我有一个表单的参数文件
parameter-name parameter-value
Run Code Online (Sandbox Code Playgroud)
参数可以按任何顺序排列,但每行只有一个参数.我想用一个新值替换一个参数的参数值.
我正在使用之前发布的行替换函数(在Python中搜索并替换文件中的一行)来替换使用python的string.replace(pattern,subst)的行.我正在使用的正则表达式在vim中工作,但似乎不能在string.replace中工作.这是我正在使用的正则表达式:
line.replace("^.*interfaceOpDataFile.*$/i", "interfaceOpDataFile %s" % (fileIn))
Run Code Online (Sandbox Code Playgroud)
其中interfaceOpDataFile是我要替换的参数名称(/ i表示不区分大小写),新参数值是fileIn变量的内容.有没有办法让python识别这个正则表达式,否则还有另一种方法可以完成这个任务吗?
And*_*ark 521
str.replace() v2 | v3无法识别正则表达式.
要使用正则表达式执行替换,请使用re.sub() v2 | v3.
例如:
import re
line = re.sub(
r"(?i)^.*interfaceOpDataFile.*$",
"interfaceOpDataFile %s" % fileIn,
line
)
Run Code Online (Sandbox Code Playgroud)
在循环中,最好先编译正则表达式:
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
Run Code Online (Sandbox Code Playgroud)
Jac*_*cki 346
您正在寻找re.sub功能.
import re
s = "Example String"
replaced = re.sub('[ES]', 'a', s)
print replaced
Run Code Online (Sandbox Code Playgroud)
将打印 axample atring
kpi*_*pie 14
作为总结
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
Run Code Online (Sandbox Code Playgroud)
Nel*_*z11 10
re.sub绝对是你要找的.所以你知道,你不需要锚和通配符.
re.sub(r"(?i)interfaceOpDataFile", "interfaceOpDataFile %s" % filein, line)
Run Code Online (Sandbox Code Playgroud)
将做同样的事情 - 匹配看起来像"interfaceOpDataFile"的第一个子串并替换它.
| 归档时间: |
|
| 查看次数: |
715838 次 |
| 最近记录: |