正则对象的match方法
match(string[, pos[, endpos]])
string:匹配使用的文本,
pos: 文本中正则表达式开始搜索的索引。及开始搜索string的下标
endpos: 文本中正则表达式结束搜索的索引。
如果不指定pos,默认是从开头开始匹配,如果匹配不到,直接返回None
import re
#每一个()是一个组,
reg = re.compile(r'(hello w.*)(hello c.*)')
#想要匹配到aa需要在前面继续加上正则
reg1= re.compile(r'\w*(hello w.*)(hello c.*)')
a='hello word hello chao'
a1='aahello word hello chao'
result = reg.match(a)
result1 = reg1.match(a1)
print(result.groups())
print(result1.groups())
(‘hello word ‘, ‘hello chao’)
(‘hello world ‘, ‘hello chao’)
正则对象的search方法
search(string[, pos[, endpos]])
这个方法用于查找字符串中可以匹配成功的子串。从string的pos下标处起尝试匹配pattern,如果pattern结束时仍可匹配,则返回一个Match对象;若无法匹配,则将pos加1后重新尝试匹配;直到pos=endpos时仍无法匹配则返回None。
import re
pattern = re.compile(r'(hello w.*)(hello c.*)')
#aa开头匹配不到的话继续往下个下标找,直到找到为止
result1 = pattern.search(r'aahello world hello chao')
print(result1.groups())
(‘hello world ‘, ‘hello chao’)
正则对象的split方法
split(string[, maxsplit])
按照能够匹配的子串将string分割后返回列表。maxsplit用于指定最大分割次数,不指定将全部分割
import re
#正则分割
p=re.compile(r'\d+')
print(p.split('hello123word456'))
[‘hello’, ‘word’, ”]
正则对象的findall方法
findall(string[, pos[, endpos]])
搜索string,以列表形式返回全部能匹配的子串
import re
p=re.compile(r'\d+')
st ='hello123word456'
print(p.findall(st)
[‘123’, ‘456’]
正则对象的finditer方法
finditer(string[, pos[, endpos]])
搜索string,返回一个顺序访问每一个匹配结果(Match对象)的迭代器。
`
import re
p = re.compile(r'\d+')
for m in p.finditer('one1two2three3four4'):
print(m.group())
1
2
3
4
Match对象
Match对象是一次匹配的结果,包含了很多关于此次匹配的信息,可以使用Match提供的可读属性或方法来获取这些信息。上面的过程中多次使用了match对象,调用了他的group()和groups()等方法。
import re
prog = re.compile(r'(?P<tagname>abc)(.*)(?P=tagname)')
result1 = prog.match('abchellowordabc')
print(result1)
print(result1.groups())
print result1.group('tagname')
print(result1.group(2))
print(result1.groupdict())
<_sre.SRE_Match object at 0x00000000031C2140>
(‘abc’, ‘helloword’)
abc
helloword
{‘tagname’: ‘abc’}
1, 我们可以看到result1已经由字符串转换成了一个正则对象。
2, resule.groups()可以查看出来所有匹配到的数据,每个()是一个元素,最终返回一个tuple
3, group()既可以通过下标(从1开始)的方式访问,也可以通过分组名进行访问。
4, groupdict只能显示有分组名的数据