阅读量:104
findall() 是 Python 中正则表达式模块 re 的一个函数,用于在字符串中查找所有与正则表达式匹配的子串。它返回一个包含所有匹配项的列表。如果没有找到匹配项,则返回一个空列表。
以下是 findall() 函数的基本用法:
- 首先,导入
re模块:
import re
- 定义一个正则表达式模式。例如,我们要查找所有的数字:
pattern = r'\d+'
这里,\d 表示数字,+ 表示匹配一个或多个数字。
- 使用
re.findall()函数在字符串中查找所有匹配项:
text = "There are 123 apples and 456 oranges in the basket."
matches = re.findall(pattern, text)
- 打印匹配结果:
print(matches) # 输出:['123', '456']
注意,findall() 返回的结果是字符串列表。如果需要将结果转换为整数列表,可以使用列表推导式:
int_matches = [int(match) for match in matches]
print(int_matches) # 输出:[123, 456]
这就是 Python 中 findall() 函数的基本用法。