findall 方法

findall 是 Python 中 re 模块提供的一个正则表达式方法,用于在字符串中查找所有匹配的子串,并以列表形式返回所有匹配结果。

基本语法

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

参数说明

  • pattern: 要匹配的正则表达式模式
  • string: 要在其中搜索的字符串
  • flags: 可选参数,用于控制正则表达式的匹配方式(如忽略大小写、多行匹配等)

返回值

返回字符串中所有与模式匹配的非重叠匹配项的列表。如果没有找到匹配项,则返回空列表。

示例

import re

# 查找所有数字
text = "There are 3 apples and 5 oranges."
numbers = re.findall(r'\d+', text)
print(numbers)  # 输出: ['3', '5']

# 查找所有单词
words = re.findall(r'\w+', text)
print(words)  # 输出: ['There', 'are', '3', 'apples', 'and', '5', 'oranges']

# 查找特定模式的电子邮件
emails = "Contact us at [email protected] or [email protected]"
email_pattern = r'[\w\.-]+@[\w\.-]+'
found_emails = re.findall(email_pattern, emails)
print(found_emails)  # 输出: ['[email protected]', '[email protected]']

注意事项

  1. 如果正则表达式中有分组(使用括号),findall 会返回分组的内容而不是整个匹配
  2. 匹配是非重叠的,即一个匹配不会包含在另一个匹配中
  3. 对于大文本,考虑使用 re.finditer() 以迭代器方式处理,节省内存

与 search 和 match 的区别

  • search: 查找字符串中任意位置的第一个匹配
  • match: 只在字符串开头查找匹配
  • findall: 查找所有匹配项

你可能感兴趣的:(python,python)