Python - AI 助手

Python re.findall() 方法



Python 的 `re.findall()` 方法將字串中模式的所有不重疊匹配項作為字串列表返回。如果模式包含捕獲組,則 `re.findall()` 返回包含匹配組的元組列表。

`re.findall()` 方法接受三個引數,例如模式、要搜尋的字串和修改搜尋行為的標誌。

`re.search()` 或 `re.match()` 方法只返回第一個匹配項,而 `re.findall()` 方法查詢所有匹配項,使其對於從文字中提取模式的多個例項非常有用。

語法

以下是 Python `re.findall()` 方法的語法和引數:

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

引數

以下是 python `re.findall()` 方法的引數:

  • **pattern:** 要搜尋的正則表示式模式。
  • **string:** 要在其內搜尋的字串。
  • **flags(可選):** 這些標誌修改匹配行為。

返回值

此方法返回字串中模式的所有不重疊匹配項的列表。

示例 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']
python_modules.htm
廣告