Python string.replace正则表达式[重复]
- 2025-02-18 09:23:00
- admin 原创
- 107
问题描述:
我有一个以下形式的参数文件:
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 识别这个正则表达式,或者还有其他方法来完成这个任务?
解决方案 1:
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
解决方案 2:
您正在寻找re.sub函数。
import re
s = "Example String"
replaced = re.sub('[ES]', 'a', s)
print(replaced)
将打印axample atring
解决方案 3:
总结
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
解决方案 4:
re.sub
绝对是你要找的。所以你知道,你不需要锚点和通配符。
re.sub(r"(?i)interfaceOpDataFile", "interfaceOpDataFile %s" % filein, line)
将做同样的事情 - 匹配第一个看起来像“interfaceOpDataFile”的子字符串并替换它。
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD