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). ...
随机推荐
- 数据库html 数据的分句
Python 中文分句 - CSDN博客 https://blog.csdn.net/laoyaotask/article/details/9260263 # 设置分句的标志符号:可以根据实际需要进行 ...
- ubuntu 查看进程,查看服务
jiqing@Ubuntu:~$ sudo netstat -anpl | grep :3306 tcp6 0 0 :::3306 :::* LISTEN 1532/mysqld jiqing@Ubu ...
- IOException 简单解决方法
java.lang.IllegalStateException异常解决方法 这个异常大多数是由文件读取,下载时抛出,但是偶尔也会由类型转换时异常抛出此异常. 错误:Optional int param ...
- javaEE框架获取和传参要使用的类和接口
1:spring 2:struts2获取前台数据(action中获取) //4修改用户密码. public String updateUserPassword() throws Exception{ ...
- poj1200Crazy Search(hash)
题目大意 将一个字符串分成长度为N的字串.且不同的字符不会超过NC个.问总共有多少个不同的子串. /* 字符串hash O(n)枚举起点 然后O(1)查询子串hash值 然后O(n)找不一样的个数 ...
- IOC框架---什么是IOC
1 IoC理论的背景 我们都知道,在采用面向对象方法设计的软件系统中,它的底层实现都是由N个对象组成的,所有的对象通过彼此的合作,最终实现系统的业务逻辑. ...
- ACM_Cipher(异或运算)
Cipher Time Limit: 2000/1000ms (Java/Others) Problem Description: 只剩两个小时就要正式开始第一次月赛了,大四师兄决定还是来出一道,找点 ...
- Ubuntu下搭建repo服务器(二): 配置git-daemon-run
git-daemon-run实际是一个脚本管理工具,用来启动git-daemon. 1 安装git-daemon-run(A端) apt-get install git-daemon-run 2. 配 ...
- c/c++ 参数传递 - 数组
对于函数参数中的数组类型:传递的是数组地址,可以理解成传递的是对数组的引用.不是值传递,这是由C/C++函数实现机制决定的.一下三种函数生命完全等价: void func(int array[10]) ...
- JS高级——作用域链
基本概念 1.只要是函数就可以创造作用域 2.函数中又可以再创建函数 3.函数内部的作用域可以访问函数外部的作用域 4.如果有多个函数嵌套,那么就会构成一个链式访问结构,这就是作用域链 <scr ...