Python re.findall() メソッド
re.findall()は、Pythonreモジュール内で使用され、すべての一致項目を検索する関数です。
文字列全体をスキャンし、正規表現に一致するすべての部分文字列をリスト形式で返します。
単語の意味: find allは「すべてを検索する」という意味です。
基本構文とパラメータ
re.findall()モジュールレベルの関数です。
構文形式
re.findall(pattern, string, flags=0)
パラメータの説明
- pattern:正規表現パターン
- string:検索対象の文字列
- flags:オプション、正規表現フラグ
関数の説明
- 戻り値:すべての一致する文字列を含むリストを返します。一致するものがない場合は空のリストを返します。
- 特徴:最初のものだけでなく、すべての一致項目を返します。
実例
例 1:すべての数字を検索
実例
import re
text = "私はリンゴを3個、オレンジを5個、バナナを8本持っています"
# すべての数字を検索
result = re.findall(r'\d+', text)
print("見つかった数字:", result)
text = "私はリンゴを3個、オレンジを5個、バナナを8本持っています"
# すべての数字を検索
result = re.findall(r'\d+', text)
print("見つかった数字:", result)
実行結果の予想:
找到的数字: ['3', '5', '8']
例 2:すべての単語を検索
実例
import re
text = "Python is powerful, Python is easy"
# すべての "Python" を検索
result = re.findall(r'Python', text)
print("見つかったPython:", result)
text = "Python is powerful, Python is easy"
# すべての "Python" を検索
result = re.findall(r'Python', text)
print("見つかったPython:", result)
実行結果の予想:
找到的Python: ['Python', 'Python']
例 3:グループを使用して複数の内容を抽出
実例
import re
text = "メール: [email protected], メール: [email protected]"
# グループを使用してユーザー名とドメイン名を同時に抽出
result = re.findall(r'(\w+)@(\w+\.\w+)', text)
print("見つかったメールアドレス:", result)
text = "メール: [email protected], メール: [email protected]"
# グループを使用してユーザー名とドメイン名を同時に抽出
result = re.findall(r'(\w+)@(\w+\.\w+)', text)
print("見つかったメールアドレス:", result)
実行結果の予想:
找到的邮箱: [('test', 'example.com'), ('admin', 'test.org')]
例 4:すべての携帯電話番号を検索
実例
import re
text = "張三: 138-1234-5678, 李四: 139-9876-5432, 王五: 137-5555-8888"
# すべての携帯電話番号を検索
result = re.findall(r'\d{3}-\d{4}-\d{4}', text)
print("すべての携帯電話番号:", result)
text = "張三: 138-1234-5678, 李四: 139-9876-5432, 王五: 137-5555-8888"
# すべての携帯電話番号を検索
result = re.findall(r'\d{3}-\d{4}-\d{4}', text)
print("すべての携帯電話番号:", result)
実行結果の予想:
所有手机号: ['138-1234-5678', '139-9876-5432', '137-5555-8888']
その他の拡張
Python re モジュール