python -re库
正则表达式的语法
正则表达式语法由字符和操作符构成
正则表达式的常用操作符:
print("--正则表达式常用操作符--") mata="11356352135 abcdefghmnopqrstuvwxyz ASDSAD112 3ASDASD" def set_compile(typ): reg=re.compile(typ) if reg.findall(mata): return reg.findall(mata) else: return'None' #.任何单个字符 print(set_compile('.')) #['1', '1', '3', '5', '6', '3', '5', '2', '1', '3', '5', ' ……] #[]字符集 print(set_compile('[abc]')) #abc单个字符 ['a', 'b', 'c'] print(set_compile('[a-z]')) #a-z的单个字符 ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] #[^]非字符集排除 print(set_compile('[^a-z]'))#非a-z小写的单个字符 ['1', '1', '3', '5', '6', '3' 'A', 'S', 'D'……] # 对前一个字符进行操作扩展(字符*、字符?、字符+) # * 前一个字符0次或无限次扩展 (扩展了除字符本身外以及空字符) #* abc* 表示ab abc abcc、c无穷次 print(set_compile('.*?'))#.*?所有的字符 #['11356352135 abcdefghmnopqrstuvwxyz ASDSAD112 3ASDASD'] # + 前一个字符1次或无限次扩展 #abc+ 表示abc、abcc、abcccc、c出现无穷多次 print(set_compile('.+')) #原字符串 print(set_compile('a*'))#['', '', '', '', '', '', '', '', '', '', '', '', '', '', 'a', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '']'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''] print(set_compile('a+'))#['a'] #?前一个字符0次或1次无限次扩展 #abc? 表示ab 和abc 字符扩展有限制 print(set_compile('a?'))#['', '', '', '', '', '', '', '', '', '', '', '', '', '', 'a', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''] #| A|B, A 和 B 可以是任意正则表达式 abc|wed 表示abc、wed 可以在[]字符集中 print(set_compile('a|b')) #['a', 'b'] print(set_compile("[a|b]")) #{m}扩展前一个字符m次 ab{2}c表示abbc math=re.search('ad{2}c','ad123addc') print(math.group()) #addc #限定字符串位置 #^ 匹配字符串开头 ^abc表示abc且在一个字符串的开头 #$ 匹配字符串结尾 abc$表示abc在一个字符的结尾 #()分组标记,内部只能使用|操作符 (abc)表示abc ,(abc|def)表示abc或者def #\d 数字、等价于[0-9] #\w 单词字符,等价于[A-Za-z 0-9]
正则表达式
|
对应字符串
|
P(Y|YT|YTH|YTHO)?N
|
'PN'、'PYN'、'PYTN'、'PYTHN'、'PYTHON'
|
PYTHON +
|
'PYTHON'、'PYTHONN'......
|
PY[TH]ON
|
'PYTON' 'PYHON'
|
PY[^TH]?ON 只要不是TH的取值范围都可以放在PY和ON之间
|
'PYON'、'PYHON'、'PYaON'......
|
PY{:3}N 表示Y有0-3之间的个数(扩展0-3次)
|
'PN'、'PYN'、'PYYN'、'PYYYN'
|
经典正则表达式实例 |
|
^[A-Za-z]+$
|
由26个字母组成的字符串
|
^[A-Za-z0-9]+$
|
由26个字母和数字组成的字符串
|
^-?\d+$
|
整数形式字符串
|
^[0-9]*[1-9][0-9]*$
|
正整数形式的字符串
|
[1-9]\d{5}
|
中国境内邮政编码 6位
|
[\u4e00-\u9fa5]
|
匹配中文字符
|
\d{3}-\d{8}|\d{4}-\d{7}
|
国内电话号码:010-68913536
|
应用:匹配ip地址的正则表达式
0-99:[1-9]?\d 100-199:1\d{2} 200-249:2[0-4]\d 250-255:25[0-5]
(([1-9]?\d|1\d{2}|2[0-4]\d|25[0-5]).){3}([1-9]?\d|1\d{2}|2[0-4]\d|25[0-5])
re.库的基本使用
re模块可以直接使用无需安装
表示类型raw string 类型(原生字符串类型) r’ ‘ ;string类型更繁琐
函数 | 说明 | 返回数据类型 |
re.search() | 从一个字符串中搜索匹配正则表达式的第一个位置(扫描整字符串返回得到的第一个值(若有多个)) | match对象;没有匹配返回None |
re.match() | 从一个字符串的开始位置起匹配正则表达式(只有在0位置匹配成功的话才有返回) | match对象;没有匹配返回None |
re.findall() | 搜索字符串,以列表类型返回全部能匹配的子串 | 列表;没有匹配返回[] |
re.split() | 将一个字符串按照正则表达式匹配结果进行分割 | 列表 |
re.finditer() | 搜索字符串,返回一个匹配结果的迭代类型,每个迭代元素是match对象 | 代元素是match对象 |
re.sub() | 在一个字符串中替代所有匹配正则表达式的子串 | 返回替换后的字符串 |
一、re.search()
re.search(pattern,string,flags=0)
在一个字符串中搜索匹配正则表达式的第一个位置,返回match对象
pattern:正则表达式的字符串或原生字符串表示
string:待匹配字符串
flags:正则表达式使用时的控制标记
常用flags:
re.I re.IGNORECASE:忽略正则表达式的大小,[A-Z]能够匹配小写字符
re.M re.MULTILINE : 正则表达式中的^(字符串的开始部位)操作符,能够将给定字符串的每行当做匹配开始(字符串是文章时)
re.S re.DOTALL :正则表达式中的.操作符能够匹配所有字符串,默认匹配除换行外的所有字符
print('-----re.search-----')
ma="dasdasddSDASD10120120 sdasd1 2321351 aSDAD1313131 dsadasd dsdsd dasdasdda"
print(re.search(r'[A-Z]{5}', ma,flags=re.I).group(0))
#dasda 匹配忽略大小写a-z中的字符串
match=re.search(r'[A-Z]{5}', ma,flags=re.M)
if match:
print(match.group(0))
#SDASD
print(re.search(r'[A-Z]{5}', ma,flags=re.S).group(0))
二、re.match( )
re.match(pattern,string,flags=0)
从一个字符串开始位置起匹配正则表达式,返回match对象
pattern:正则表达式的字符串或原生字符串表示
string:待匹配字符串
flags:正则表达式使用时的控制标记
print('------re.match-----')
match=re.match(r'\d{6}','BIT 100081')
if match:
print(match.group())
else:
print('None') #返回None
match2=re.match(r'[1-9]\d{5}','100081 bts')
if match2:
print(match2.group(0)) #100081
三、re.findall( )
re.findall(pattern,string,flags=0)
搜索字符串,以列表类型返回全部能匹配的子串
pattern:正则表达式的字符串或原生字符串表示
string:待匹配字符串
flags:正则表达式使用时的控制标记
print('-------re.findall----------')
findall='1234564654sdasda12356ads1a3dasda123135dasdasda123131'
print(re.findall(r'\d{6}', findall)) #['123456', '123135', '123131']
四、re.split( )
re.split(pattern,string,maxsplit=0,flags=0)
将一个字符串按照正则表达式匹配结果进行分割,返回列表类型。
pattern:正则表达式的字符串或原生字符串表示
string:待匹配字符串
maxsplit:最大分割数,剩余部分作为最后一个元素输出
flags:正则表达式使用时的控制标记
print('--------split---------')
split='123123qwe456789eqw123456qewwqe78985123'
print(re.split(r'\d{6}',split)) #['', 'qwe', 'eqw', 'qewwqe', '23']
#maxsplit的用法
print(re.split(r'\d{6}',split,maxsplit=2)) #['', 'qwe', 'eqw123456qewwqe78985123'] 按照字符划分两次,之后的部分作为一整个字符串
五、re.finditer( )
re.split(pattern,string,flags=0)
搜索字符串,返回一个匹配结果的迭代类型,每个迭代元素是match对象
pattern:正则表达式的字符串或原生字符串表示
string:待匹配字符串
flags:正则表达式使用时的控制标记
print('---------re.finditer-------------')
finditer='123123qwe123456qew789456qwe789466'
print(type(re.finditer('\d{6}',finditer))) #<class 'callable_iterator'>
for i in re.finditer('\d{6}',finditer):
print(i.group())
"""
123123
123456
789456
789466
"""
a=next(re.finditer('\d{6}',finditer))
print(a.group()) #123123
六、re.sub( )
re.sub(pattern,repl,string,count=0,flags=0)
在一个字符串中替代所有匹配正则表达式的子串,返回新字符串
pattern:正则表达式的字符串或原生字符串表示
repl:替换匹配字符串的字符串(替换字符串)
string:待匹配字符串
count:匹配的最大替换次数
flags:正则表达式使用时的控制标记
print("-----------re.sub-------------------")
sub='123123qwe123456QWE789456qwe789466qwe13456qwe1345561qwe'
#把qwe替换为QQQ
print(re.sub(r'[A-Z]{3}', 'QQQ', sub, flags=re.I)) #123123QQQ123456QQQ789456QQQ789466QQQ13456QQQ1345561QQQ
#使用count限定替换数量
print(re.sub(r'[A-Z]{3}', 'QQQ', sub, count=2,flags=re.I)) #123123QQQ123456QQQ789456qwe789466qwe13456qwe1345561qwe这里只更换了两个qwe
七.re库的另一种等价用法面向对象的用法
函数式用法:一次性操作 ret=re.search(r'[1-9]\d{5}’,’BIT 1008611′)
面向对象用法:编译后的多次操作
pat=re.compile(r'[1-9]\d{5}’)
rst=pat.search(‘BIT 10008611’)
八.regex=re.compile(pattern,flags=0)
将正则表达式的字符串形式编译成正则表达式对象
pattern:正则表达式的字符串或原生字符串表示
flags:正则表达式使用时的控制标记
返回对象类型:#<class ‘re.Pattern’>
print('----regex=re.compile()-----') compile_re='132456qwe789456qwe466147' regex=re.compile('\d{6}') print(type(regex)) #<class 're.Pattern'> #应用 print('---------regex.(search()/match()/findall()/finditer()/split()/sub())----------') print(regex.search(compile_re).group()) #132456 print(regex.match(compile_re).group()) #132456 print(regex.findall(compile_re)) #['132456', '789456', '466147'] print(next(regex.finditer(compile_re)).group()) #132456 print(regex.split(compile_re,maxsplit=1)) #['', 'qwe789456qwe466147']
re库的Match对象(如:search,match返回的对象)
match对象的属性:
match对象的方法
print('-----------match对象的属性和方法---------------------') #表示match对象:match_obj1 & match_obj2 search='123456qwe123456qew789456qwe741852qwe963140' match_obj1=re.search('\d{6}',search) reg=re.compile('\d{6}') match_obj2=reg.search(search) print(match_obj1,match_obj2) #<re.Match object; span=(0, 6), match='123456'> <re.Match object; span=(0, 6), match='123456'> #match对象的属性: #.re属性 print(match_obj1.re) #re.compile('\\d{6}') #.string 待匹配的文本 print(match_obj1.string) #123456qwe123456qew789456qwe741852qwe963140 #.pos 正则表达式搜索文本的开始位置(读取指针在字符串最开始的位置) print(match_obj1.pos) #0 <class 'int'> #.endpos正则表达式搜索文本的结束位置 (读取指针在字符串结束位置) print(match_obj1.endpos) #42 <class 'int'> print(type(match_obj1.endpos)) #<class 'int'> print(len(search)) #42 #match对象的方法: #.group(0) 获取匹配后的字符串 print(match_obj1.group()) #123456 #.start()匹配的字符串在原字符串的开始位置 print(match_obj1.start()) #0 #.end()匹配的字符串在原字符串的结束位置 print(match_obj1.end()) #6 #.span() 返回(.start(),.end()) print(match_obj1.span()) #(0, 6)
re库的贪婪匹配和最小匹配
#re的贪婪匹配 match=re.search(r'PY.*N','PYANBNCNDN') print(match.group()) # PYANBNCNDN默认输出最长的 #re的最小匹配 ? match=re.search(r'PY.*?N','PYANBNCNDN') print(match.group()) #PYAN ? 的使用 #最小匹配操作符 """ 最小匹配操作符 *? 前一个字符0次或无限次扩展,最小匹配 +? 前一个字符1次或无限次扩展,最小匹配 ?? 前一个字符0次或1次扩展,最小匹配 {m,n}?扩展前一个字符m至n(含n),最小匹配