python的正则表达式re模块的常用方法


Posted in Python onMarch 09, 2013

1.re的简介
使用python的re模块,尽管不能满足所有复杂的匹配情况,但足够在绝大多数情况下能够有效地实现对复杂字符串的分析并提取出相关信息。python 会将正则表达式转化为字节码,利用 C 语言的匹配引擎进行深度优先的匹配。

import re 
print re.__doc__

可以查询re模块的功能信息,下面会结合几个例子说明。

2.re的正则表达式语法

正则表达式语法表如下:

语法 意义 说明
"." 任意字符
"^" 字符串开始 '^hello'匹配'helloworld'而不匹配'aaaahellobbb'
"$" 字符串结尾 与上同理
"*"  0 个或多个字符(贪婪匹配) 匹配chinaunix
"+" 1 个或多个字符(贪婪匹配) 与上同理
"?" 0 个或多个字符(贪婪匹配) 与上同理
*?,+?,?? 以上三个取第一个匹配结果(非贪婪匹配) 匹配
{m,n} 对于前一个字符重复m到n次,{m}亦可 a{6}匹配6个a、a{2,4}匹配2到4个a
{m,n}? 对于前一个字符重复m到n次,并取尽可能少 ‘aaaaaa'中a{2,4}只会匹配2个
"\\" 特殊字符转义或者特殊序列
[] 表示一个字符集 [0-9]、[a-z]、[A-Z]、[^0]
"|" A|B,或运算
(...) 匹配括号中任意表达式
(?#...) 注释,可忽略
(?=...) Matches if ... matches next, but doesn't consume the string. '(?=test)'  在hellotest中匹配hello
(?!...) Matches if ... doesn't match next. '(?!=test)'  若hello后面不为test,匹配hello
(? Matches if preceded by ... (must be fixed length). '(?
(? Matches if not preceded by ... (must be fixed length). '(?

正则表达式特殊序列表如下:
特殊序列符号 意义
\A 只在字符串开始进行匹配
\Z 只在字符串结尾进行匹配
\b 匹配位于开始或结尾的空字符串
\B 匹配不位于开始或结尾的空字符串
\d 相当于[0-9]
\D 相当于[^0-9]
\s 匹配任意空白字符:[\t\n\r\r\v]
\S 匹配任意非空白字符:[^\t\n\r\r\v]
\w 匹配任意数字和字母:[a-zA-Z0-9]
\W 匹配任意非数字和字母:[^a-zA-Z0-9]

3.re的主要功能函数

    常用的功能函数包括:compile、search、match、split、findall(finditer)、sub(subn)
compile
re.compile(pattern[, flags])
作用:把正则表达式语法转化成正则表达式对象
flags定义包括:
re.I:忽略大小写
re.L:表示特殊字符集 \w, \W, \b, \B, \s, \S 依赖于当前环境
re.M:多行模式
re.S:' . '并且包括换行符在内的任意字符(注意:' . '不包括换行符)
re.U: 表示特殊字符集 \w, \W, \b, \B, \d, \D, \s, \S 依赖于 Unicode 字符属性数据库

search
re.search(pattern, string[, flags])
search (string[, pos[, endpos]])
作用:在字符串中查找匹配正则表达式模式的位置,返回 MatchObject 的实例,如果没有找到匹配的位置,则返回 None。

match
re.match(pattern, string[, flags])
match(string[, pos[, endpos]])
作用:match() 函数只在字符串的开始位置尝试匹配正则表达式,也就是只报告从位置 0 开始的匹配情况,而 search() 函数是扫描整个字符串来查找匹配。如果想要搜索整个字符串来寻找匹配,应当用 search()。

下面是几个例子:
例:最基本的用法,通过re.RegexObject对象调用

#!/usr/bin/env python
import re
r1 = re.compile(r'world')
if r1.match('helloworld'):
    print 'match succeeds'
else:
    print 'match fails'
if r1.search('helloworld'):
    print 'search succeeds'
else:
    print 'search fails'

说明一下:r是raw(原始)的意思。因为在表示字符串中有一些转义符,如表示回车'\n'。如果要表示\表需要写为'\\'。但如果我就是需要表示一个'\'+'n',不用r方式要写为:'\\n'。但使用r方式则为r'\n'这样清晰多了。

例:设置flag

#r2 = re.compile(r'n$', re.S)
#r2 = re.compile('\n$', re.S)
r2 = re.compile('World$', re.I)
if r2.search('helloworld\n'):
    print 'search succeeds'
else:
    print 'search fails'

例:直接调用
if re.search(r'abc','helloaaabcdworldn'):
    print 'search succeeds'
else:
    print 'search fails'

split
re.split(pattern, string[, maxsplit=0, flags=0])
split(string[, maxsplit=0])
作用:可以将字符串匹配正则表达式的部分割开并返回一个列表
例:简单分析ip

#!/usr/bin/env python
import re
r1 = re.compile('W+')
print r1.split('192.168.1.1')
print re.split('(W+)', '192.168.1.1')
print re.split('(W+)', '192.168.1.1', 1)

结果如下:
['192', '168', '1', '1']
['192', '.', '168', '.', '1', '.', '1']
['192', '.', '168.1.1']

findall
re.findall(pattern, string[, flags])
findall(string[, pos[, endpos]])
作用:在字符串中找到正则表达式所匹配的所有子串,并组成一个列表返回
例:查找[]包括的内容(贪婪和非贪婪查找)

#!/usr/bin/env python
import re
r1 = re.compile('([.*])')
print re.findall(r1, "hello[hi]heldfsdsf[iwonder]lo")
r1 = re.compile('([.*?])')
print re.findall(r1, "hello[hi]heldfsdsf[iwonder]lo")
print re.findall('[0-9]{2}',"fdskfj1323jfkdj")
print re.findall('([0-9][a-z])',"fdskfj1323jfkdj")
print re.findall('(?=www)',"afdsfwwwfkdjfsdfsdwww")
print re.findall('(?<=www)',"afdsfwwwfkdjfsdfsdwww")

finditer
re.finditer(pattern, string[, flags])
finditer(string[, pos[, endpos]])
说明:和 findall 类似,在字符串中找到正则表达式所匹配的所有子串,并组成一个迭代器返回。同样 RegexObject 有:

sub
re.sub(pattern, repl, string[, count, flags])
sub(repl, string[, count=0])
说明:在字符串 string 中找到匹配正则表达式 pattern 的所有子串,用另一个字符串 repl 进行替换。如果没有找到匹配 pattern 的串,则返回未被修改的 string。Repl 既可以是字符串也可以是一个函数。
例:

#!/usr/bin/env python
import re
p = re.compile('(one|two|three)')
print p.sub('num', 'one word two words three words apple', 2)

subn
re.subn(pattern, repl, string[, count, flags])
subn(repl, string[, count=0])

说明:该函数的功能和 sub() 相同,但它还返回新的字符串以及替换的次数。同样 RegexObject 有:

Python 相关文章推荐
Python去掉字符串中空格的方法
Mar 11 Python
通过数据库向Django模型添加字段的示例
Jul 21 Python
Python向日志输出中添加上下文信息
May 24 Python
Django项目中用JS实现加载子页面并传值的方法
May 28 Python
Python3数据库操作包pymysql的操作方法
Jul 16 Python
Windows下安装Scrapy
Oct 17 Python
用pycharm开发django项目示例代码
Jun 13 Python
python多线程高级锁condition简单用法示例
Nov 07 Python
Python大数据之网络爬虫的post请求、get请求区别实例分析
Nov 16 Python
关于python 跨域处理方式详解
Mar 28 Python
keras的ImageDataGenerator和flow()的用法说明
Jul 03 Python
Python3安装模块报错Microsoft Visual C++ 14.0 is required的解决方法
Jul 28 Python
Python语言编写电脑时间自动同步小工具
Mar 08 #Python
py2exe 编译ico图标的代码
Mar 08 #Python
python中wx将图标显示在右下角的脚本代码
Mar 08 #Python
python中关于时间和日期函数的常用计算总结(time和datatime)
Mar 08 #Python
python中关于日期时间处理的问答集锦
Mar 08 #Python
python局部赋值的规则
Mar 07 #Python
Python 用户登录验证的小例子
Mar 06 #Python
You might like
javascript window.opener的用法分析
2010/04/07 Javascript
扩展easyui.datagrid,添加数据loading遮罩效果代码
2010/11/02 Javascript
jquery常用方法及使用示例汇总
2014/11/08 Javascript
jQuery对象与DOM对象之间的相互转换
2015/03/03 Javascript
JS实现在状态栏显示打字效果完整实例
2015/11/02 Javascript
谈谈js中的prototype及prototype属性解释和常用方法
2015/11/25 Javascript
NodeJS实现阿里大鱼短信通知发送
2016/01/17 NodeJs
JS+CSS3实现超炫的散列画廊特效
2016/07/16 Javascript
使用纯JS代码判断字符串中有多少汉字的实现方法(超简单实用)
2016/11/12 Javascript
微信小程序之ES6与事项助手的功能实现
2016/11/30 Javascript
jquery仿京东商品放大浏览页面
2017/06/06 jQuery
js canvas实现简单的图像扩散效果
2020/06/28 Javascript
Thinkphp5微信小程序获取用户信息接口的实例详解
2017/09/26 Javascript
详解nodeJs文件系统(fs)与流(stream)
2018/01/24 NodeJs
使用Angular material主题定义自己的组件库的配色体系
2019/09/04 Javascript
如何实现vue的tree组件
2020/12/03 Vue.js
使用scrapy实现爬网站例子和实现网络爬虫(蜘蛛)的步骤
2014/01/23 Python
pandas每次多Sheet写入文件的方法
2018/12/10 Python
pandas DataFrame 数据选取,修改,切片的实现
2020/04/24 Python
TensorFlow固化模型的实现操作
2020/05/26 Python
详解python UDP 编程
2020/08/24 Python
python 实现围棋游戏(纯tkinter gui)
2020/11/13 Python
解决python的空格和tab混淆而报错的问题
2021/02/26 Python
HTML5本地数据库基础操作详解
2016/04/26 HTML / CSS
从零实现一个自定义html5播放器的示例代码
2017/08/01 HTML / CSS
html5中canvas图表实现柱状图的示例
2017/11/13 HTML / CSS
猫途鹰:全球领先的旅游点评社区
2017/04/07 全球购物
Myprotein瑞典官方网站:畅销欧洲英国运动营养品牌
2018/01/22 全球购物
医院门卫岗位职责
2013/12/30 职场文书
数控机械专业个人的自我评价
2014/01/02 职场文书
音乐教学随笔感言
2014/02/19 职场文书
高级销售求职信
2014/02/21 职场文书
司仪主持词两篇
2014/03/22 职场文书
保护黄河倡议书
2014/05/16 职场文书
新闻编辑求职信
2014/07/13 职场文书
《分一些蚊子进来》读后感3篇
2020/01/09 职场文书