Python之re方法
1.re的matche和search方法
#!/usr/bin/env python # -*- coding:utf8 -*- # @Time : 2017/11/15 13:41 # @Author : hantong # @File : re1.py #正则对象的match匹配 import re reg = re.compile(r'(\w*hello w.*)(hello l.*)') print(dir(reg)) a = 'hello world hello ling' result = reg.match(a) print(result) print(result.groups()) b = 'aa' + a print(b) result2 = reg.match(b) print(result2) print(result2.groups()) #正则对象的search方法比较,建议使用match(match搭配正则表达式实现比较精准搜索) #search是全局搜索,精度较低 m = 'dffkhjwjjweewwel' print('####################'*2) mm = reg.search(b) print(mm) print(mm.groups())执行结果:
['__class__', '__copy__', '__deepcopy__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__',
'findall', 'finditer', 'flags', 'groupindex', 'groups', 'match', 'pattern', 'scanner', 'search', 'split', 'sub', 'subn']
<_sre.SRE_Match object at 0x000000000267C0B8>
('hello world ', 'hello ling')
aahello world hello ling
<_sre.SRE_Match object at 0x000000000267C140>
('aahello world ', 'hello ling')
########################################
<_sre.SRE_Match object at 0x000000000267C1C8>
('aahello world ', 'hello ling')
2.re的split,findall,finditer方法
#!/usr/bin/env python # -*- coding:utf8 -*- # @Time : 2017/11/15 14:10 # @Author : hantong # @File : re2.py import re p = re.compile(r'\d+') str1 = 'one1two2three3four4' #正则对象的split方法,使用正则匹配进行分隔字符串 print(p.split(str1)) #正则对象的findall方法,来查找符合对象的子字符串 #返回值是列表 print(p.findall(str1)) #与split取值刚好相反 print('########')*10 for i in p.finditer(str1): print(i) #此时的i是一个match对象 print(i.group())执行结果:
['one', 'two', 'three', 'four', '']
['1', '2', '3', '4']
################################################################################
<_sre.SRE_Match object at 0x0000000001DAC510>
1
<_sre.SRE_Match object at 0x000000000257A718>
2
<_sre.SRE_Match object at 0x0000000001DAC510>
3
<_sre.SRE_Match object at 0x000000000257A718>
4
3.re的matche对象
#!/usr/bin/env python # -*- coding:utf8 -*- # @Time : 2017/11/15 14:22 # @Author : hantong # @File : match1.py import re prog = re.compile(r'(?P<tagname>abc)(.*)(?P=tagname)') result1 = prog.match('abclfjlad234sjldabc') print(result1) #result1已经由字符串转换成了一个正则对象 print(result1.groups()) #resule.groups()可以查看出来所有匹配到的数据,每个()是一个元素,最终返回一个tuple print(result1.group('tagname')) print(result1.group(2)) #group()既可以通过下标(从1开始)的方式访问,也可以通过分组名进行访问。 print(result1.groupdict()) #groupdict只能显示有分组名的数据 #group([group1, …]): #获得一个或多个分组截获的字符串;指定多个参数时将以元组形式返回。 #group1可以使用编号也可以使用别名;编号0代表整个匹配的子串;不填写参数时,返回group(0); # 没有截获字符串的组返回None;截获了多次的组返回最后一次截获的子串。 #groups([default]): #以元组形式返回全部分组截获的字符串。相当于调用group(1,2,…last)。default表示没有截获字符串的组以这个值替代,默认为None。 #groupdict([default]): #返回以有别名的组的别名为键、以该组截获的子串为值的字典,没有别名的组不包含在内。default含义同上。执行结果:
<_sre.SRE_Match object at 0x0000000002555140>
('abc', 'lfjlad234sjld')
abc
lfjlad234sjld
{'tagname': 'abc'}