5.2.2 re模块方法与正则表达式对象
Python标准库re提供了正则表达式操作所需要的功能,既可以直接使用re模块中的方法,来实现,也可以把模式编译成正则表达式对象再使用。
方法 | 功能说明 |
complie(pattern[,flagss]) | 创建模式对象 |
search(pattern,string[,flags]) | 在整个字符串中寻找模板,返回match对象或None |
match(pattern,string[,flags]) | 从字符串开始处匹配模式,返回match对象或None |
findall(pattern,string[,flags]) | 列出字符串中模式的所有匹配项 |
split(pattern,string[,maxsplit=0]) | 根据模式匹配项分隔字符串 |
sub(pat,repl,string[,count=0]) | 将字符串中所有pat的匹配项用repl替换 |
escape(string) | 将字符串中所有特殊正则表达式字符转义 |
其中,函数参数flags的值可以是re.I(表示忽略大小写)、re.L(表示支持本地字符集)、re.M(多行匹配模式)、re.S(使元字符"."匹配任意字符,包括换行符)、re.U(匹配Unicode字符)、re.X(忽略模式中的空格,并可以使用#注释)的不同组合(使用"|"进行组合)。
1 直接使用re模块
>>> import re
>>> text = 'alpha.beta...gamma delta' #测试用的字符串
>>> re.split('[\. ]+',text) #使用指定字符作为分隔符进行字符串拆分
['alpha', 'beta', 'gamma', 'delta']
>>>
>>> re.split('[\. ]+',text,maxsplit=2) #最多分隔两次
['alpha', 'beta', 'gamma delta']
>>>
>>> re.split('[\. ]+',text,maxsplit=1) #最多分隔一次
['alpha', 'beta...gamma delta']
>>>
>>> pat = '[a-zA-Z]+'
>>> re.findall(pat,text) #查找所有单词
['alpha', 'beta', 'gamma', 'delta']
>>>
>>> pat = '{name}'
>>> text = 'Dear {name}...'
>>> re.sub(pat,'Mr.Dong',text) #字符串替换
'Dear Mr.Dong...'
>>>
>>> s = 'a s d'
>>> re.sub('a|s|d','goog',s)
'goog goog goog'
>>>
>>> re.escape('http://www.python.org') #字符串转义
'http\\:\\/\\/www\\.python\\.org'
>>>
>>> print(re.match('done|quit','done')) #匹配成功,返回mathc对象
<_sre.SRE_Match object; span=(0, 4), match='done'>
>>>
>>> print(re.match('done|quit','done!'))
<_sre.SRE_Match object; span=(0, 4), match='done'>
>>>
>>> print(re.match('done|quit','doe')) #匹配不成功返回,返回空值None
None
>>>
>>> print(re.search('done|quit','d!one!done')) #匹配成功
<_sre.SRE_Match object; span=(6, 10), match='done'>
>>>
下面的代码使用不同的方法删除字符串中多余的空格,如果遇到连续多个空格子只保留一个,同时删除字符串两侧的所有空白字符。
>>> import re
>>> s = 'aaa bb c d e fff '
>>> ' '.join(s.split()) #不适用正则表达式,直接使用字符串对象的方法
'aaa bb c d e fff'
>>>
>>> re.split('[\s]+',s)
['aaa', 'bb', 'c', 'd', 'e', 'fff', '']
>>>
>>> re.split('[\s]+',s.strip()) #同时使用re模块中的方法和字符串对象方法
['aaa', 'bb', 'c', 'd', 'e', 'fff']
>>>
>>> ' '.join(re.split('[\s]+',s.strip()))
'aaa bb c d e fff'
>>>
>>> ' '.join(re.split('\s+',s.strip()))
'aaa bb c d e fff'
>>>
>>>
>>> #直接使用re模块的字符串替换方法
>>> re.sub('\s+',' ',s.strip())
'aaa bb c d e fff'
>>>
下面的代码使用以"\"开头的元字符来实现字符串的特定搜索。
>>> import re
>>> example = 'ShanDong Institute of Business and Technology is a very beautiful school.'
>>>
>>> re.findall('\\ba.+?\\b',example) #以字母a开头的完整单词,“?”表示非贪心模式
['and', 'a ']
>>>
>>> re.findall('\\ba.+\\b',example) #贪心模式的匹配结果
['and Technology is a very beautiful school']
>>>
>>> re.findall('\\ba\w* \\b',example)
['and ', 'a ']
>>>
>>> re.findall('\\Bo.+?\\b',example) #不以o开头且含有o字母的单词剩余部分
['ong', 'ology', 'ool']
>>>
>>> re.find('\\b\w.+?\\b',example) #所有单词
Traceback (most recent call last):
File "<pyshell#39>", line 1, in <module>
re.find('\\b\w.+?\\b',example) #所有单词
AttributeError: module 're' has no attribute 'find'
>>>
>>> re.findall('\\b\w.+?\\b',example) #所有单词
['ShanDong', 'Institute', 'of', 'Business', 'and', 'Technology', 'is', 'a ', 'very', 'beautiful', 'school']
>>>
>>> re.findall('\w+',example) #所有单词
['ShanDong', 'Institute', 'of', 'Business', 'and', 'Technology', 'is', 'a', 'very', 'beautiful', 'school']
>>>
>>> re.findall(r'\b\w.+?\b',example) #使用原始字符串
['ShanDong', 'Institute', 'of', 'Business', 'and', 'Technology', 'is', 'a ', 'very', 'beautiful', 'school']
>>>
>>> re.split('\s',example) #使用任何空白字符分隔字符串
['ShanDong', 'Institute', 'of', 'Business', 'and', 'Technology', 'is', 'a', 'very', 'beautiful', 'school.']
>>>
>>> re.findall('\d+\.\d+\.\d+','Python 2.7.11') #查找并返回x.x.x形式的数字
['2.7.11']
>>>
>>> re.findall('\d+\.\d+\.\d+','Python 2.7.11,Python 3.5.1')
['2.7.11', '3.5.1']
>>>
2 使用正则表达式对象
首先使用re模块的compile()方法将正则表达式编译生成正则表达式对象,然后再使用正则表达式对象提供的方法进行字符串处理。使用编译后的正则表达式对象不仅可以提高字符串处理速度,还提供了更加强大的字符串处理功能。
正则表达式对象的match(string[,pos[,endpos]])方法用于在字符串开头或指定位置进行搜索,模式必须出现在字符串开头或指定位置;serach(string[,pos[,endpos]])方法用于在整个字符串或指定范围中进行搜索;findall(string[,pos[endpos]])方法用于在字符串中查找所有符合正则表达式的字符串并以列表形式返回。
>>> import re
>>> example = 'ShanDong Institute of Business and Technology'
>>>
>>> #编译正则表达式对象,查找以B开头的单词
>>> pattern = re.compile(r'\bB\w+\b')
>>>
>>> #使用正则表达式的findall()方法
>>> pattern.findall(example)
['Business']
>>>
>>> #查找以字母g结尾的单词
>>> pattern = re.compile(r'\w+g\b')
>>> pattern.findall(example)
['ShanDong']
>>>
>>> #查找3个字母长的单词
>>> pattern = re.compile(r'\b[a-zA-Z]{3}\b')
>>> pattern.findall(example)
['and']
>>>
>>> #从字符串开头开始匹配,失败返回空值
>>> pattern.match(exampke)
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
pattern.match(exampke)
NameError: name 'exampke' is not defined
>>>
>>> pattern.match(example)
>>>
>>> #从整个字符串中搜索,成功
>>> pattern,search(example)
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
pattern,search(example)
NameError: name 'search' is not defined
>>> pattern.search(example)
<_sre.SRE_Match object; span=(31, 34), match='and'>
>>>
>>> #查找所有含有字母a的单词
>>> pattern = re.compile(r'\b\w*a\w* \b')
>>> pattern.findall(example)
['ShanDong ', 'and ']
>>>
>>>
>>> text = 'He was carefully disguised but captured quickly by police.'
>>>
>>> #查找所有以字母组合ly结尾的单词
>>> re.findall(r'\w+ly',text)
['carefully', 'quickly']
>>>
正则表达式对象的sub(repl,string[,count=0])和subn(repl,string[,count=0])方法来实现字符串替换功能。
>>> import re
>>> example = '''Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.'''
>>> #正则表达式对象,匹配以b或B开头的单词
>>> pattern = re.compile(r'\bb\w* \b',re.I)
>>>
>>> #将符合条件的单词替换为*
>>> pattern.sub('*',example)
'*is *than ugly.\nExplicit is *than implicit.\nSimple is *than complex.\nComplex is *than complicated.\nFlat is *than nested.\nSparse is *than dense.\nReadability counts.'
>>>
>>> #只替换一次
>>> pattern.sub('*',example,1)
'*is better than ugly.\nExplicit is better than implicit.\nSimple is better than complex.\nComplex is better than complicated.\nFlat is better than nested.\nSparse is better than dense.\nReadability counts.'
>>>
>>> #匹配以字母b开头的单词
>>> pattern = re.compile(r'\bb\w* \b')
>>> #将符合条件的单词替换为*,只替换一次
>>> pattern.sub('*',example)
'Beautiful is *than ugly.\nExplicit is *than implicit.\nSimple is *than complex.\nComplex is *than complicated.\nFlat is *than nested.\nSparse is *than dense.\nReadability counts.'
>>>
正则表达式对象的split(string[,maxsplit=0)方法用来实现字符串分隔。
>>> import re
>>>
>>> example = r'one,two,three.four/five\six?seven[eight]nine|ten'
>>>
>>> pattern = re.compile(r'[,./\\?[\]\|]')
>>>
>>> pattern.split(example)
['one', 'two', 'three', 'four', 'five', 'six?seven', 'eight', 'nine', 'ten']
>>>
>>> example = r'one1two2three3four4five5six6seven7eight8nine9ten'
>>> #使用数字分隔符
>>> pattern = re.compile(r'\d+')
>>> pattern.split(example)
['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']
>>>
>>>
>>> pattern = re.compile(r'[\s,.\d]+') #允许分隔符重复
>>> pattern.split(example)
['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']
>>>
3 match 对象
正则表达式模块或正则表达式对象的match()方法和search()方法匹配成功后都会返回match对象。
match()对象的主要方法有:
group()(返回匹配的一个或多个子模式内容)、
groups()(返回一个包含匹配的所有子模式内容的元组)、
groupdict()(返回包含匹配的所有命名子模式内容的字典)、
start()(返回指定子模式内容的起始位置)、
end()(返回指定子模式内容的结束位置的前一个位置)、
span()(返回一个包含指定子模式内容起始位置和结束位置的前一个位置的元组)等。
下面的代码使用几种不同的方法来删除字符串中指定的内容。
>>> import re
>>> email = "tony@tiremove_thisger.net"
>>>
>>> #使用search()方法返回的match对象
>>>
>>> m = re.search("remove_this",email)
>>>
>>> #字符串切片
>>> email[:m.start()] + email[m.end():]
'tony@tiger.net'
>>>
>>> #直接使用re模块的sub()方法
>>> re.sub('remove_this','',email)
'tony@tiger.net'
>>>
>>> #也可以使用字符串替换方法
>>> email .replace('remove_this','')
'tony@tiger.net'
>>>
下面的代码演示了match对象的group()、groups()与groupdict()以及其他方法的用法:
>>> m = re.match(r'(\w+)(\w+)','Isaac Newton,physicist')
>>> #返回整个模式内容
>>> m.group(0)
'Isaac'
>>> m = re.match(r'(\w+) (\w+)','Isaac Newton,physicist')
>>> m.group(0)
'Isaac Newton'
>>>
>>> #返回第1个子模式内容
>>> m.group(1)
'Isaac'
>>>
>>> #返回第2个子模式内容
>>> m.group(2)
'Newton'
>>>
>>> #返回指定的多个子模式内容
>>> m.group(1,2)
('Isaac', 'Newton')
>>>
下面的代码演示了子模式扩展语法的用法:
>>> import re
>>>
>>> #使用命名子模式
>>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)","Malcolm Reynolds")
>>> m.group('first_name')
'Malcolm'
>>>
>>> m.group('last_name')
'Reynolds'
>>>
>>> m = re.match(r'(\d+)\.(\d+)','24.1632')
>>> m.groupdict() #以字典形式返回匹配的结果
{}
>>> m.groups() #返回所有匹配的子模式(不包括第0个)
('', '')
>>>
>>>
>>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)","Malcolm Reynolds")
>>> #以字典形式返回匹配结果
>>> m.groupdict()
{'first_name': 'Malcolm', 'last_name': 'Reynolds'}
>>>
>>>
>>>
>>>
>>> exampleString = '''There should be one--and preferabley only one --obvious way to do it.
Although taht way not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than right now.'''
>>> pattern = re.compile(r'(?<=\w\s)never(?=\s\w)') #查找不在句子开头和结尾的never
>>> matchResult = pattern.search(exampleString)
>>> matchResult.span()
(168, 173)
>>>
>>>
>>> #查找位于句子末尾的单词
>>> pattern = re.compile(r'(?<=\w\s)never') #查找位于句子末尾的单词
>>> matchResult = pattern.search(exampleString)
>>> matchResult.span()
(152, 157)
>>>
>>> #查找前面是is的better than组合
>>> pattern = re.compile(r'(?:is\s)better(\sthan)')
>>>
>>> matchResult = pattern.search(exampleString)
>>> matchResult.span()
(137, 151)
>>>
>>>
>>> #组 0 表示整个模式
>>> matchResult.group(0)
'is better than'
>>>
>>> matchResult.group(1)
' than'
>>>
>>>
>>> #查找以n或N字母开头的所有单词
>>> pattern = re.compile(r'\b(?i)n\w+\b')
>>> index = 0
>>> while True:
matchResult = pattern.search(exampleString,index)
if not matchResult:
break
print(matchResult.group(0),':',matchResult.span(0))
index = matchResult.end(0) not : (88, 91)
Now : (133, 136)
never : (152, 157)
never : (168, 173)
now : (201, 204)
>>>
>>> pattern = re.compile(r'(?<!not\s)be\b') #查找前面没有单词not的单词be
5.2.2 re模块方法与正则表达式对象的更多相关文章
- python re 模块和基础正则表达式
1.迭代器:对象在其内部实现了iter(),__iter__()方法,可以用next方法实现自我遍历. 二.python正则表达式 1.python通过re模块支持正则表达式 2.查看当前系统有哪些p ...
- python正则表达式模块re:正则表达式常用字符、常用可选标志位、group与groups、match、search、sub、split,findall、compile、特殊字符转义
本文内容: 正则表达式常用字符. 常用可选标志位. group与groups. match. search. sub. split findall. compile 特殊字符转义 一些现实例子 首发时 ...
- Py修行路 python基础 (二十一)logging日志模块 json序列化 正则表达式(re)
一.日志模块 两种配置方式:1.config函数 2.logger #1.config函数 不能输出到屏幕 #2.logger对象 (获取别人的信息,需要两个数据流:文件流和屏幕流需要将数据从两个数据 ...
- 第十八天re模块和·正则表达式
1.斐波那契 # 问第n个斐波那契数是多少 def func(n): if n>2: return func(n-2)+func(n-1) else: return 1 num=int(inp ...
- APM飞控修改数传模块方法
APM飞控修改数传模块方法 硬件 ARDUCOPTER第二代 数传模块(USB接口) 数传模块(telem接口) usb-ttl模块 修改方法 注意:APM固件版本和数传模块估计版本是分开的,但有一定 ...
- python模块之re正则表达式
41.python的正则表达式 1. python中re模块提供了正则表达式相关操作 字符: . 匹配除换行符以外的任意字符 \w 匹配字母或数字或下划线或汉字 \W大写代表非\w ...
- javascript操作正则表达式对象的方法总结
//正则表达式对象 /* var s = 'good good study day day up '; var r, re; re = new RegExp('study',"g" ...
- python import自定义模块方法
转自:http://www.cnitblog.com/seeyeah/archive/2009/03/15/55440.html python包含子目录中的模块方法比较简单,关键是能够在sys.pat ...
- JavaScript match()方法和正则表达式match()
先介绍参数为普通字符串的使用方式,此时match方法的返回值是存放首次匹配内容的数组.如果没有找到匹配结果,返回null.语法结构: 1 str.match(searchvalue)参数解析:(1). ...
随机推荐
- 从基于 SQL 的 CURD 操作转移到基于语义 Web 的 CURD 操作
中文名称 CURD 含义 数据库技术中的缩写词 操作对象 一般的项目开发的各种参数 作用 用于处理数据的基本原子操作 它代表创建(Create).更新(Update).读取(Retrieve) ...
- oc76--NSMutableDictionary
// // main.m // NSMutableDictionary // NSDictionary不可变,初始化后就不可以修改,NSMutableDictionary可变,初始化后可以改变. // ...
- innerxml and outerxml
xml文件如下 <root> <a></a> <b></b> <c></c> <a></a> ...
- UVALive 4671 K-neighbor substrings 巧用FFT
UVALive4671 K-neighbor substrings 给定一个两个字符串A和B B为模式串.问A中有多少不同子串与B的距离小于k 所谓距离就是不同位的个数. 由于字符串只包含a和 ...
- 洛谷P1613 跑路(最短路+倍增)
P1613 跑路 题目描述 小A的工作不仅繁琐,更有苛刻的规定,要求小A每天早上在6:00之前到达公司,否则这个月工资清零.可是小A偏偏又有赖床的坏毛病.于是为了保住自己的工资,小A买了一个十分牛B的 ...
- Akka源码分析-Remote-位置透明
上一篇博客中,我们研究了remote模式下如何发消息给远程actor,其实无论如何,最终都是通过RemoteActorRef来发送消息的.另外官网也明确说明了,ActorRef是可以忽略网络位置的,这 ...
- js 调用微信浏览器内置方法,启动支付
$.post("{php echo app_url('pay/cash')}",{orderno:orderno,paytype:paytype},function(m){ //t ...
- idea git项目修改后无法提交 颜色都是灰色
现象: idea git项目修改后无法提交 修改后的文件提交时不显示 颜色都是灰色 分析问题出现的原因: git未识别idea下项目. 排查: 发现是因为这个项目之前是基于svn的,然后直接导入 ...
- 快速搭建Hadoop及HBase分布式环境
本文旨在快速搭建一套Hadoop及HBase的分布式环境,自己测试玩玩的话ok,如果真的要搭一套集群建议还是参考下ambari吧,目前正在摸索该项目中.下面先来看看怎么快速搭建一套分布式环境. 准备 ...
- JS——祝愿墙
注意事项: 1.for循环的下一层注册了事件的话,事件函数中关于变量i的节点元素是不允许出现的,因为在函数加载的时候,只会加载函数名,不会加载函数体,外层for循环会走完一边,变量i一直会停留在最后一 ...