Python 正则替换字符串
来源:互联网 发布:黑魂3白狼捏脸数据 编辑:程序博客网 时间:2024/06/06 03:32
说明
需求:
1. 替换给定字符串中符合正则匹配的子串。
2. 使用者配置增加、删减替换规则方便。
3. 基于装饰器模式实现。
实现
基于re包和装饰器模式实现。
参考装饰器模式,这资料挺不错的,有人把设计模式用python都实现了一遍。
邮箱正则匹配:
email_regex = r'[0-9a-zA-Z_]{0,19}@[0-9a-zA-Z]{1,13}\.(?:com|cn|net)'
网址正则匹配:
url_regex = r"\"?http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+\"?"
日期正则匹配:
date_regex_standard = r"\d{1,4}[./-]\d{1,2}[./-]\d{1,2}.\d{1,2}[./: -]\d{1,2}[./: -]\d{1,2}"
ip正则匹配:
ip_regex = r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"
代码如下:
# -*- coding: utf-8 -*-import reimport sysreload(sys)email_regex = r'[0-9a-zA-Z_]{0,19}@[0-9a-zA-Z]{1,13}\.(?:com|cn|net)'url_regex = r"\"?http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+\"?"ip_regex = r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"ip_port_regex = r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d{1,5}"date_regex_standard = r"\d{1,4}[./-]\d{1,2}[./-]\d{1,2}.\d{1,2}[./: -]\d{1,2}[./: -]\d{1,2}"class LogText(object): def __init__(self, text): self._text = text def get_log(self): return self._textclass EmailWrapper(object): def __init__(self, log_text): self.log_text = log_text self.wrap_log = None def get_log(self): """ 整体匹配即可,匹配邮箱 """ return re.sub(email_regex, '$email$', self.log_text.get_log())class UrlWrapper(object): def __init__(self, log_text): self.log_text = log_text def get_log(self): """ 整体匹配即可,用于匹配url """ return re.sub(url_regex, '$url$', self.log_text.get_log())class DataStandardWrapper(object): def __init__(self, log_text): self.log_text = log_text def get_log(self): """ 匹配2016*09*25*03*16*20形式日期,其中*代表空格、'/'、'-'、':'、'.'等符号。 """ return re.sub(date_regex_standard, '$date$', self.log_text.get_log())class IpWrapper(object): def __init__(self, log_text): self.log_text = log_text def get_log(self): """ 整体匹配即可,先匹配ip+端口号,再匹配ip """ return re.sub(ip_regex, '$ip$', re.sub(ip_port_regex, '$ip+port$', self.log_text.get_log()))if __name__ == "__main__": log_text = LogText('fff@163.comdssd得到http://www.baiddu.com方法2016-07-09 09:21:23擦撒fff@163.comhttp://www.baidu.com') log_text_wrap = DataStandardWrapper(EmailWrapper(UrlWrapper(log_text))) print log_text_wrap.get_log() log_text_wrap = UrlWrapper(EmailWrapper(log_text)) print log_text_wrap.get_log()
运行结果
1 0
- 【python】 字符串替换+正则
- Python 正则替换字符串
- Python正则表达式如何进行字符串替换
- Python正则表达式如何进行字符串替换
- Python正则表达式如何进行字符串替换
- Python正则表达式如何进行字符串替换
- 字符串替换之正则替换
- Python 正则表达式替换特定字符为标志的字符串
- python中的正则替换字符串函数re.sub
- python 正则表达式 字符串的 匹配 替换 分割 查找
- python正则表达式使用实例-替换字符串HTML标签
- Python 正则表达式 字符串的匹配、替换、分割、查找
- Python 正则表达式匹配字符串替换、格式修改
- 对字符串正则替换
- 对字符串正则替换
- 正则表达式替换字符串
- js 正则替换字符串
- js字符串正则替换
- 浅谈javabean,.内省机制
- 《等一个人咖啡》
- Ubuntu安装zsh
- Activity的四种启动模式及其应用场景
- JAVA笔记之继承
- Python 正则替换字符串
- 软考复习 Internet及应用
- JS/Jquery版本的俄罗斯方块(Tetris)
- class<T>和 class<?>类型 有什么区别
- 蓝桥杯比赛javaB组练习《饮料换购》
- asp.net跨域单点击登录
- 团体程序设计天梯赛-练习集 L1阶段 全部题解
- 数位DP入门-SCOI2009
- cocos2d-x-3.14.1时序图