python正则表达式使用实例-替换字符串HTML标签

最近因为需要把字符串中的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)):
                    print "matched:%s" %match_list[i]
                line = pattern.sub('', line)
                print line

输入文件

 helle<p>world</p><br/>

输出结果

matched:p
matched:/p
matched:br/
helleworld

这里说一下,Python的re模块的findall函数返回的是正则模式里面组所匹配的内容,可以方便进一步使用。

欢迎点击

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值