python正则表达式的使用方法
来源:互联网 发布:微信js分享demo 编辑:程序博客网 时间:2024/05/19 04:52
python正则表达式的使用方法
python提供正则表达式的库。
import re
re库中提供的compile,match,search,split,findall
是常用的方法。
compile
将正则表达式模式编译成一个正则表达式的对象,用于使用它去匹配match和search方法,使用这个函数的优点就是可以
在单个程序中可以重复的使用。
prog = re.compile(parrent)result = prog.match(string)# 相当于result = re.match(pattern, string)
match
re.match(parrent, string, flag=0)
适用于在字符串的开头的零个或更多字符匹配正则表达式,将返回一个MatchObject的实例,如果没有匹配的字符串,则返回None。
match,只能匹配单行,如果需要匹配的字符串是多行的,也只匹配第一行。
import reresouce = 'lee lee lee 'prog = re.compile(r'le+')print type(prog)result = prog.match(resouce)print result.group()'''output<type '_sre.SRE_Pattern'><_sre.SRE_Match object at 0x000000000304A510>lee'''
search
re.search(pattern, string, flag=0)
扫描字符串,寻找第一个由正则表达式产生匹配的位置,返回一个MatchObject实例,返回None说明字符串中没有匹配的子串。
split
re.split(pattern, string, maxsplit=0, flag=0)
把字符串根据正则表达式进行拆分,放在一个list中。
import reresouce = 'tee lee lee 'prog = re.compile(r'\W+')print type(prog)result = prog.split(resouce)print result'''output<type '_sre.SRE_Pattern'>['tee', 'lee', 'lee', '']'''
findall
re.findall(pattern, string, flag=0)
从左向右的扫描,匹配按照发现的顺序返回到一个list中,空匹配则就返回一个空的list。
import reresouce = 'tee lee lee 'prog = re.compile(r'le+')print type(prog)result = prog.findall(resouce)print result'''output<type '_sre.SRE_Pattern'>['lee', 'lee']'''
阅读全文
0 0
- python正则表达式的使用方法
- Python 正则表达式 RE模块的使用方法
- Python 正则表达式 RE模块的使用方法
- Python正则表达式re模块的使用方法
- 正则表达式的使用方法
- 常用的正则表达式使用方法
- php正则表达式的使用方法
- 正则表达式的基本使用方法
- python正则表达式介绍及使用方法
- [Python] re(正则表达式) 模块使用方法
- python的正则表达式
- python 的正则表达式
- Python的正则表达式
- Python的正则表达式
- Python的正则表达式
- python的正则表达式
- Python的正则表达式
- python的正则表达式
- LRU算法的小型缓存
- 新人新篇
- C++中方括号[]的作用总结
- matlab 求素数(三种方法)
- 基于centos 搭建 LAMP 环境,建立WordPress站点
- python正则表达式的使用方法
- 循环链表的简单使用
- 20170925_数据库查询结构
- 最小二乘法 (Least Squares Method, LS)
- python基本数据类型
- linux用户管理
- Ubuntu 16.04 上的 NGINX Web 服务器!
- Reflection2017.9.25
- 欢迎使用CSDN-markdown编辑器