所以我有一个我正在构建的脚本,用来替换我正在重建和重命名的一个非常大的配置文件中的单词。因此,我将举一个例子来说明这是怎么回事。让我们假设在负载均衡器配置的服务器行中,我有"web01“,并希望将其更改为"web01_svr",它工作得很好。但是在"add service“行,我可能会有"web01-80-HTTP_sg”。脚本插入自身,使其成为"web01_svr-80-HTTP_sg“。如何在此脚本中指定仅匹配精确对象,而不匹配部分对象?
with open('massiveconfig.txt', 'r') as file :
filedata = file.read()替换目标字符串
while True:
old = input("What is the old name you would like to replace?: ")
new = input("What is the new name you would like to replace the old
with?: ")
filedata = filedata.replace(old, new)
cont = input("Would you like to replace another?: Y/n")
# Write the file out again
with open('massiveconfig.txt', 'w') as file:
file.write(filedata)发布于 2018-01-09 07:02:59
Regex来拯救你:
import re
filedata = re.sub(r'\b'+ old +r'\b(?![-])', new, filedata)你不是很具体,哪些特殊字符可能会出现在你的单词中。我假设,_或.是可以预期的。在这种情况下,您可以调整脚本并使用[-_.]而不是[-]
https://stackoverflow.com/questions/48157245
复制相似问题