Python re 模块

Python re.findall() 函数用于找出所有匹配,返回列表。

语法

re.findall(pattern, string)

参数

pattern:正则表达式。第二个参数 string:要搜索的字符串。可选 flags

返回值

返回所有匹配的列表。有分组时返回分组元组列表。

示例

import re

text = "价格: 12元, 34元, 56元"
print(re.findall(r"\d+", text))        # ['12', '34', '56']

emails = "a@x.com b@y.com"
print(re.findall(r"\w+@\w+\.\w+", emails))  # ['a@x.com', 'b@y.com']

# 有分组时返回分组
text2 = "2024-01-15 2024-02-20"
print(re.findall(r"(\d+)-(\d+)-(\d+)", text2))
# [('2024', '01', '15'), ('2024', '02', '20')]

注意事项

有分组时 findall 返回分组元组列表。要所有匹配值用它最方便。