Python re.findall() 方法以字符串列表的形式返回字符串中模式的所有非重叠匹配项。如果模式包括捕获组,则 re.findall() 返回包含匹配组的 Tuples 列表。
re.findall() 方法接受三个参数,例如模式、要搜索的字符串和用于修改搜索行为的标志。
方法 re.search() 或 re.match() 仅返回第一个匹配项,而方法 re.findall() 通过使其可用于从文本中提取模式的多个实例来查找所有匹配项。
语法
以下是 Python re.findall() 方法的语法和参数 -
re.findall(pattern, string, flags=0)
参数
以下是 python re.findall() 方法的参数 -
- pattern:要搜索的正则表达式模式。
- string:要在其中搜索的字符串。
- flags(可选):这些标志修改匹配行为
返回值
此方法返回字符串中 pattern 的所有非重叠匹配项的列表。
示例 1
以下是使用 re.findall() 方法的基本示例。在这个例子中,模式 '\d+' 用于查找字符串中的所有数字序列,方法 re.findall() 返回所有匹配项的列表 -
import re
result = re.findall(r'\d+', 'There are 123 apples and 456 oranges.')
print(result)
输出
['123', '456']
示例 2
在此示例中,模式 '\b\w+\b' 用于查找字符串中的所有单词。它返回一个单词列表 -
import re
result = re.findall(r'\b\w+\b', 'Hello, world! Welcome to Python.')
print(result)
输出
['Hello', 'world', 'Welcome', 'to', 'Python']
示例 3
在这个例子中,re.MULTILINE 标志允许 '^' 匹配多行字符串中每行的开头。re.findall() 方法返回每行的所有匹配项 -
import re
text = """Hello
hello
HELLO"""
result = re.findall(r'^hello', text, re.IGNORECASE | re.MULTILINE)
print(result)
输出
['Hello', 'hello', 'HELLO']