您的位置:首页 > 编程语言 > Python开发

Python——正则表达式 re模块

2018-09-16 20:59 483 查看
Python的正则表达式
Python中使用re模块提供了正则表达式处理的能力
常量



使用 | 位或 运算开启多种选项
方法
import re
编译
re.compile(pattern, flags=0)
设定flags、编译模式,返回正则表达式对象 regex。
pettern就是正则表达式字符串,flags是选项,正则表达式需要被编译,为了提高效率,这些写编译后的结果被保存,下次使用同的pattern的时候,就不需要再次版编译
re的其它方法为了提高效率都调用了编译方法,就是为了提速
单次匹配
re.match(pattern,string,flags=0)
regex.match(string [,pos [,endpos]])
返回match对象
match匹配从字符串的开头匹配,regex对象match方法可以重设定个开始位置和结束位置。
re.search(pattern,string,flags=0)
regex.search(string [,pos [,endpos]])
返回match对象
从头搜索直到第一个匹配,regex对象serch方法可以冲设定开始位置和结束位置。
re.fullmatch(pattern,string,flags=0)
regex.fullmatch(string [,pos [,endpos]])
返回match对象
整个字符串和正则表达式匹配
全文搜索
re.findall(pattren,string,flags=0)
rege
b60
x.findall(string [, pos [,endpos]])
对整个字符串,从左至右,返回左右匹配项的列表
如果pattern使用组,则列表元素为组的匹配内容,不使用组,则元素为匹配内容
re.findeiter(pattern,striing,flags=0)
regex,finditer(string [,pos [,endpos]])
对整个字符串,从左至右,返回所有匹配项,返回迭代器
注意:迭代出来的元素为match对象
匹配替换
re.sub(pattern,replacement,string,count=0,flags=0)
regex.sub(replacement,string,count=0)
返回new_string
使用pattern 对字符串string 进行匹配,对匹配项使用replacement替换
repalcement可以是string、bytes、function
re.subn(pattern,replacement,string,count=0,flags=0)
regex.subn(replacement,string,count=0)
同re.sub 返回一个元组(new_string , number_of_sub_made)
分割字符串
字符串的分割函数split , 太难用,不能指定多个字符进行分割
re.split(pattern,string,maxsplit=0,flags=0)
regex.split(string,maxsplit=0)
分组
使用小括号的pattern捕获的数据被放到了组group中。
match、search 函数可以返回match对象;findall 返回字符串列表;finditer返回一个个match对象
如果pattern中使用了分组,如果有匹配的结果,会在match对象中:
1.使用,group(n)方式返回对应分组,1~N 是对应的分组,0返回整个匹配的字符串
2.如果使用了命名分组没,可以使用group(“name”)的方式获取分组
3.也可以使用groups()返回所有分组
4.使用groupdict()返回所有命名的分组
matchaer.group() 返回 字符串
matchaer.group(‘name’) 返回 字符串
matcher.groups() 返回 分组组成的tuple
matcher.groupdict()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  re 模块 正则