背景:日志中有打印出明文密碼,需要將密碼不分替換為*
關鍵語句就一條:
re.sub(r'--password .? ', '--password * ', line)
用途是,找到--password關鍵字,然后替換后面兩個空格之間的內容為
import re
def log_mask(self):
raw_file = self.LOG_PATH + self.logfile_name + '_tmp.log'
mask_file = self.LOG_PATH + self.logfile_name + '.log'
with open(raw_file, "r", encoding="utf-8") as f1, open(mask_file, "w", encoding="utf-8") as f2:
for line in f1:
f2.write(re.sub(r'--password .*? ', '--password * ', line))
os.remove(raw_file)
如果打算用相同的模式執行重復替換,可以考慮先將模式編譯以獲得更好的性能。
實例:
import re
text='今天是:11/28/2018'
datepat=re.compile(r'(\d+)/(\d+)/(\d+)')
print(datepat.sub(r'\3-\1-\2',text))
print(text)
實例2
把大於兩個以上的換行替換為兩個換行
pat = re.compile(r'\n\n+')
result = pat.sub('\n\n', result)