最近因為需要把字符串中的html標簽替換掉,想到的是使用正則來做,因為原來模塊是用C++碼的,所以就用的glibc的regex來做的。后來查資料發現用python來做這件事,簡單方便,而且一次性可以完成所有替換,不想用C還需要自己寫程序移動指針完成替換。不多說了上代碼,很簡單。
#! /usr/bin/env python # -*- coding:gbk -*- """ Notes: A python script that use regex to replace all the label of a html file """ import os import sys import re if __name__ == "__main__": input_file = sys.argv[1] with open(input_file, 'r') as fp: for line in fp: line = line.rstrip() pattern = re.compile(r'<([^>]*)>') match_list = pattern.findall(line) for i in range(0, len(match_list)): 輸入文件 helle<p>world</p><br/>輸出結果
matched:pmatched:/pmatched:br/helleworld這里說一下,Python的re模塊的findall函數返回的是正則模式里面組所匹配的內容,可以方便進一步使用。
新聞熱點
疑難解答