之前文章中有过goups()、group()的使用,其实为了更方便使用匹配结果,可以在匹配时使用“?P<>”,获得匹配结果后调用.groupdict()方法,获得字典类型的结果。
# coding:utf-8
'''
Note:
re库笔记
Author:Qred
Date:2019/7/23
'''
import re
telephone = '0571-10010'
res = re.search('(?P<Area>.*)-(?P<Phone>.*)', telephone)
# 通过?P<Area> 指定字典的key
if res != None:
print type(res)
print res.groups()
# 匹配结果元组格式输出
print type(res.groups())
print res.group()
print type(res.group())
print res.groupdict()
# 获得字典类型的匹配结果
print type(res.groupdict())
得到的结果: