Python re.finditer() 方法
re.finditer() 是 Python re 模块中用于迭代查找所有匹配项的函数。
它返回一个迭代器,每个元素都是一个 match 对象,可以逐个处理匹配结果。
单词释义: find iter 是查找迭代器的意思。
基本语法与参数
语法格式
re.finditer(pattern, string, flags=0)
参数说明
- pattern:正则表达式模式
- string:被搜索的字符串
- flags:可选,正则表达式标志
函数说明
- 返回值: 返回一个迭代器 (iterator),每个元素是一个 match 对象。
- 特点: 适合处理大量匹配结果,节省内存。
实例
示例 1:基础用法
实例
import re
text = "3个苹果,5个橙子,8个香蕉"
# 迭代查找所有数字
for match in re.finditer(r'\d+', text):
print(f"找到: {match.group()} 位置: {match.start()}-{match.end()}")
text = "3个苹果,5个橙子,8个香蕉"
# 迭代查找所有数字
for match in re.finditer(r'\d+', text):
print(f"找到: {match.group()} 位置: {match.start()}-{match.end()}")
运行结果预期:
找到: 3 位置: 0-1 找到: 5 位置: 4-5 找到: 8 位置: 8-9
示例 2:处理邮箱列表
实例
import re
text = "联系[email protected]或[email protected]获取帮助"
# 查找并处理每个邮箱
for match in re.finditer(r'(\w+)@(\w+\.\w+)', text):
print(f"完整: {match.group()}")
print(f" 用户名: {match.group(1)}")
print(f" 域名: {match.group(2)}")
print(f" 位置: {match.start()}-{match.end()}")
text = "联系[email protected]或[email protected]获取帮助"
# 查找并处理每个邮箱
for match in re.finditer(r'(\w+)@(\w+\.\w+)', text):
print(f"完整: {match.group()}")
print(f" 用户名: {match.group(1)}")
print(f" 域名: {match.group(2)}")
print(f" 位置: {match.start()}-{match.end()}")
运行结果预期:
完整: [email protected] 用户名: test 域名: example.com 位置: 2-16 完整: [email protected] 用户名: admin 域名: test.org 位置: 17-30
示例 3:与 re.findall() 对比
实例
import re
text = "a1b2c3d4"
# findall 返回字符串列表
print("findall:", re.findall(r'\d', text))
# finditer 返回迭代器
print("finditer:", [m.group() for m in re.finditer(r'\d', text)])
text = "a1b2c3d4"
# findall 返回字符串列表
print("findall:", re.findall(r'\d', text))
# finditer 返回迭代器
print("finditer:", [m.group() for m in re.finditer(r'\d', text)])
运行结果预期:
findall: ['1', '2', '3', '4'] finditer: ['1', '2', '3', '4']
Python re 模块
点我分享笔记