Python re.finditer() メソッド

Python re 模块Python re モジュール


re.finditer()は Pythonreモジュール内ですべての一致を反復検索するための関数です。

イテレータを返し、各要素は match オブジェクトで、マッチ結果を1つずつ処理できます。

単語の意味: find iter検索イテレータの意味です。


基本構文とパラメータ

構文形式

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

パラメータの説明

  • pattern:正規表現パターン
  • string:検索対象の文字列
  • flags:オプション、正規表現フラグ

関数の説明

  • 戻り値:イテレータを返します。各要素は match オブジェクトです。
  • 特徴:大量の一致結果を処理するのに適しており、メモリを節約します。

例

例1:基本的な使い方

例

import re

text = リンゴ3個、オレンジ5個、バナナ8個

# すべての数字を繰り返し検索
for match in re.finditer(r'\d+', text):
    print(f見つかりました: {match.group()} 位置: {match.start()}-{match.end()})

期待される実行結果:

找到: 3 位置: 0-1
找到: 5 位置: 4-5
找到: 8 位置: 8-9

例2:メールアドレスリストの処理

例

import re

text = [email protected]または[email protected]に連絡してヘルプを得る

# 各メールアドレスを検索して処理
for match in re.finditer(r'(\w+)@(\w+\.\w+)', text):
    print(f全体: {match.group()})
    print(fユーザー名: {match.group(1)})
    print(fドメイン名: {match.group(2)})
    print(f位置: {match.start()}-{match.end()})

期待される実行結果:

完整: [email protected]
  用户名: test
  域名: example.com
  位置: 2-16
完整: [email protected]
  用户名: admin
  域名: test.org
  位置: 17-30

例3:re.findall() との比較

例

import re

text = "a1b2c3d4"

# findall は文字列のリストを返す
print("findall:", re.findall(r'\d', text))

# finditer はイテレータを返す
print("finditer:", [m.group() for m in re.finditer(r'\d', text)])

期待される実行結果:

findall: ['1', '2', '3', '4']
finditer: ['1', '2', '3', '4']

Python re 模块Python re モジュール

その他の拡張