import re
# 1. findall() 匹配字符串中所有符合正则的字符串,并返回一个列表
result_list = re.findall(r"\d+", "我的手机号是13812345678,我的QQ号是456789123")
print(result_list, type(result_list)) # ['13812345678', '456789123'] <class 'list'>
print("==============")
# 2. finditer() 匹配字符串中所有符合正则的字符串,并返回一个迭代器
result_iter = re.finditer(r"\d+", "我的手机号是13812345678,我的QQ号是456789123")
for match in result_iter:
print(match, type(match)) # Match 对象 从Match对象中获取数据需要使用group()方法
print(match.group()) # 13812345678 456789123
print("==============")
# 3. search() 匹配字符串中第一个符合正则的字符串,并返回一个Match对象
result_match = re.search(r"\d+", "我的手机号是13812345678,我的QQ号是456789123")
print(result_match.group(), type(result_match)) # Match 对象 <class 're.Match'>
print("==============")
# 4. match() 从头开始匹配,如果字符串开始位置匹配正则表达式,返回一个Match对象,否则返回None
# 可以认为在正则的前面加上了 ^
result_match = re.match(r"\d+", "我的手机号是13812345678,我的QQ号是456789123")
try:
print(result_match.group(), type(result_match)) # 13812345678 <class 're.Match'>
except Exception:
print("NoneType类型中没有group()方法")
print("================")
# 5. 预加载正则表达式
obj = re.compile(r"\d+")
result_iter = obj.finditer("我的手机号是13812345678,我的QQ号是456789123")
for match in result_iter:
print(match.group()) # 13812345678 456789123
print("================")
# 6. 惰性匹配
s = """
<div class='jay'><span id='1'>抽烟</span></div>
<div class='jj'><span id='2'>喝酒</span></div>
<div class='jolin'><span id='3'>烫头</span></div>
<div class='sylar'><span id='4'>阿巴阿巴</span></div>
<div class='tory'><span id='5'>???</span></div>
"""
obj = re.compile(r"<div class='.*?'><span id='(?P<id>.*?)'>(?P<content>.*?)</span></div>", re.S)
result_iter = obj.finditer(s)
for match in result_iter:
print(match.group(2)) # 抽烟 喝酒 烫头 阿巴阿巴 ???
print(match.group("id"))
# 构建为字典的格式
print(match.groupdict())
标签:group,python,13812345678,re,正则,result,模块,print,match
From: https://www.cnblogs.com/lsixu/p/18399737