python 正则表达式的处理
2015-06-29 11:05
696 查看
1.基本用法
2. 分组,返回元组
3.给分组加名称,返回字典
#!/usr/bin/env python # coding=utf-8 import re # example 1 text ="fjsk test\t fjskd bar\t \ttest" regex = re.compile('\s+') print regex.split(text) # example 2 email =""" jfksdfasm@qq.com test@test.com.cn jfdskf@163.com jkmiao@yahoo.123com """ pattern = r'[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z.0-9]{2,6}' regex = re.compile(pattern,flags=re.IGNORECASE) # get all print regex.findall(email) # get the first one m = regex.search(text) # print email[m.start():m.end()] print m # replace print regex.sub('RECORD',email) 显示:
jkmiao@sysucis:~/workplace/python/test$ python regex.py ['fjsk', 'test', 'fjskd', 'bar', 'test'] ['jfksdfasm@qq.com', 'test@test.com.cn', 'jfdskf@163.com', 'jkmiao@yahoo.123com'] None RECORD RECORD RECORD RECORD
2. 分组,返回元组
#example 3 pattern = r'([A-Z0-9._%+=]+)@([A-Z0-9.-]+)\.([A-Z.]{2,5})' regex = re.compile(pattern,flags=re.IGNORECASE) m = regex.match('name@domain.suffix') print m.groups() print regex.findall(email)
# output
('name', 'domain', 'suffi') [('jfksdfasm', 'qq', 'com'), ('test', 'gamil', 'com'), ('jfdskf', '163', 'com'), ('jkmiao', 'yahoo.com', 'cn')]
3.给分组加名称,返回字典
#example 4 regex = re.compile(r""" (?P<userame>[A-Z0-9._%+-]+) @(?P<domain>[A-Z0-9.-]+) \. (?P<suffix>[A-Z0-9.]{2,4}) """,flags=re.IGNORECASE|re.VERBOSE) m = regex.match("jkmaio@sysu.com") print m.groupdict() print regex.findall(email) # output
jkmiao@sysucis:~/workplace/python/test$ python regex.py {'domain': 'sysu', 'userame': 'jkmaio', 'suffix': 'com'} [('jfksdfasm', 'qq', 'com'), ('test', 'gamil', 'com'), ('jfdskf', '163', 'com'), ('jkmiao', 'yahoo.com', 'cn')]
相关文章推荐
- Python Django 开发 2 数据库
- Python 深入理解yield
- 编写Python CGI脚本的教程
- 使用国内镜像源来加速python pypi包的安装
- python 常用包
- Python访问纯真IP数据库脚本分享
- Python Tips
- [Python] 利用Django进行Web开发系列(二)
- Python实现把数字转换成中文
- Python中if __name__ == '__main__'作用解析
- Python 文件目录操作
- Python实现函数重载
- Python 入门介绍(整理)
- windows下,python基于SocketServer模拟实现SSH(多线程版)
- Python学习笔记-遍历文件
- PAT Maximum subsequence sum (Python)
- PAT Shuffling machine (Python)
- PAT Have fun with numbers (Python)
- PAT 数组元素循环右移问题 (Python)
- PAT 素数对猜想 (Python)