ZetCode

Python re.findall() 函数

最后修改于 2025 年 4 月 20 日

re.findall 简介

re.findall 函数是 Python 的 re 模块中用于模式匹配的强大工具。它扫描字符串并返回模式的所有非重叠匹配项。

与查找第一个匹配项的 re.search 不同,findall 查找所有匹配项。它将匹配项作为字符串或元组列表返回,具体取决于模式组。

此函数非常适合从文本数据中提取模式的多个出现项。它适用于编译后的模式和原始正则表达式字符串。

基本语法

re.findall 的语法很简单

re.findall(pattern, string, flags=0)

pattern 是要匹配的正则表达式。 string 是要搜索的文本。可选的 flags 修改匹配行为。

基本模式匹配

让我们从一个简单的示例开始,查找字符串中的所有数字。

basic_findall.py
#!/usr/bin/python

import re

text = "Order 12345 shipped on 2023-05-15, delivered on 2023-05-20"
numbers = re.findall(r'\d+', text)

print("Found numbers:", numbers)

此示例查找文本中所有数字序列。 \d+ 模式匹配一个或多个数字字符。

numbers = re.findall(r'\d+', text)

findall 函数扫描整个字符串并将所有匹配项作为列表返回。每个匹配项都是一个连续数字的字符串。

查找具有特定模式的单词

我们可以使用 findall 查找与特定条件匹配的所有单词。

word_patterns.py
#!/usr/bin/python

import re

text = "The quick brown fox jumps over the lazy dog. Foxes are clever."
words = re.findall(r'\b[fF]\w+\b', text)

print("Words starting with f/F:", words)

这会查找所有以“f”或“F”开头的单词。 \b 确保我们只匹配整个单词。 \w+ 匹配单词字符。

提取电子邮件地址

findall 非常适合提取结构化数据,例如电子邮件。

emails.py
#!/usr/bin/python

import re

text = "Contact us at support@example.com or sales@company.org for help"
emails = re.findall(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', text)

print("Found emails:", emails)

此模式匹配标准电子邮件格式。它在有效字符和域后缀之间查找 @ 符号。

将组与 findall 一起使用

当模式包含组时,findall 返回组的元组。

groups.py
#!/usr/bin/python

import re

text = "John: 30, Alice: 25, Bob: 42, Eve: 29"
matches = re.findall(r'(\w+): (\d+)', text)

for name, age in matches:
    print(f"{name} is {age} years old")

这使用两个捕获组提取姓名-年龄对。每个匹配项都变成分组匹配项的元组。

不区分大小写的匹配

我们可以使用 re.IGNORECASE 标志使 findall 不区分大小写。

case_insensitive.py
#!/usr/bin/python

import re

text = "Python is great. python is versatile. PYTHON is powerful."
matches = re.findall(r'python', text, re.IGNORECASE)

print("Python mentions:", matches)

该标志使该模式匹配“python”的所有大小写变体。当大小写在搜索中无关紧要时,这很有用。

查找多个模式

我们可以使用管道字符搜索多个替代模式。

multiple_patterns.py
#!/usr/bin/python

import re

text = "Apples 5, Oranges 3, Bananas 12, Grapes 7"
matches = re.findall(r'(Apples|Oranges|Grapes)\s+\d+', text)

print("Fruit quantities:", matches)

这会查找特定的水果及其数量。 替代运算符 | 允许匹配多个模式中的任何一个。

提取 URL

findall 可以使用全面的模式从文本中提取 URL。

urls.py
#!/usr/bin/python

import re

text = "Visit https://example.com or http://test.org/page?q=1 for more info"
urls = re.findall(r'https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', text)

print("Found URLs:", urls)

此模式匹配 HTTP 和 HTTPS URL。它处理各种 URL 组件,同时避免过于复杂的匹配。

最佳实践

使用 re.findall 时,请遵循以下最佳实践

性能注意事项

re.findall 一次性将所有匹配项加载到内存中。 对于非常大的文本或大量匹配项,这可能会消耗大量内存。

对于大型文本的内存高效处理,请考虑使用 re.finditer,它将匹配项作为迭代器返回。 这会一次处理一个匹配项。

来源

Python re.findall() 文档

本教程涵盖了 Python 的 re.findall 函数的基本方面。 掌握此函数将大大增强您在 Python 中的文本处理能力。

作者

我叫 Jan Bodnar,是一位充满激情的程序员,拥有丰富的编程经验。 我从 2007 年开始撰写编程文章。到目前为止,我已经撰写了 1,400 多篇文章和 8 本电子书。 我拥有超过十年的编程教学经验。

列出所有 Python 教程