findall函数来自re模块,用于查找字符串中所有符合正则表达式的子串并以列表返回。其语法为re.findall(pattern, string, flags=0),可匹配固定字符串、数字、邮箱等,支持忽略大小写和多行处理,需使用原始字符串避免转义问题。

Python 中的 findall 函数来自 re 模块,用于在字符串中查找所有符合正则表达式的子串,并以列表形式返回。它不会只返回第一个匹配项,而是找出全部匹配内容,适合提取信息。
基本语法
使用方法如下:
re.findall(pattern, string, flags=0)- pattern:正则表达式模式
- string:要搜索的目标字符串
- flags:可选参数,如 re.IGNORECASE、re.DOTALL 等
匹配普通字符串
如果只是查找固定字符串,可以直接写文本模式。
import retext = "I love Python. Python is great."
result = re.findall("Python", text)
print(result) # 输出: ['Python', 'Python']
使用正则表达式模式
findall 更强大的地方在于支持正则语法,比如匹配数字、邮箱、特定格式等。
立即学习“Python免费学习笔记(深入)”;
- 匹配所有数字:
re.findall(r'\d+', "年龄25,工资10000") # 结果: ['25', '10000'] - 匹配邮箱示例:
email_text = "联系我 at user@example.com 或 admin@test.org"
emails = re.findall(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', email_text)
print(emails) # 输出: ['user@example.com', 'admin@test.org']
处理大小写和多行文本
通过 flags 参数可以控制匹配行为。
text = "Python python PYthon"re.findall("python", text, re.IGNORECASE) # 忽略大小写,结果: ['Python', 'python', 'PYthon']
基本上就这些。只要写出正确的正则表达式,findall 就能帮你把所有匹配内容找出来。注意使用原始字符串(r"")避免转义问题。不复杂但容易忽略细节。










