我是初学者,使用 python 编写一些脚本。我想在我的文件中将 "FQ_PARAMS" 替换为 "FQ_PARAMS_PRICING"。它运行良好,但问题是在某些文件中我已经有了这个 "FQ_PARAMS_PRICING"。所以它变成了 "FQ_PARAMS_PRICING_PRICING"。我想知道是否有一种方法可以做到不重叠。
这是我的代码:
for file in dirs:
if file.endswith('.play'):
fileComplete=dirPath+"/"+file
with open(fileComplete, "r") as myfile:
chaine=myfile.read()
result=re.sub(r'FQ_PARAMS',r'FQ_PARAMS_PRICING',chaine)
with open(fileComplete,"w") as fichier:
fichier.write(result)
请您参考如下方法:
您可以使用负向先行。所以正则表达式现在显示为:
r'FQ_PARAMS(?!_PRICING)'
for file in dirs:
if file.endswith('.play'):
fileComplete=dirPath+"/"+file
with open(fileComplete, "r") as myfile:
chaine=myfile.read()
result=re.sub(r'FQ_PARAMS<b>(?!_PRICING)</b>',r'FQ_PARAMS_PRICING',chaine)
with open(fileComplete,"w") as fichier:
fichier.write(result)
Lookahead 向前看(不消耗字符),negative lookahead 添加了一个约束,它应该不看到_PRICING 当它向前看时。只有这些项目匹配。
