Python で正規表現に一致するものをすべて見つけるにはどうすればいいですか? 質問する

Python で正規表現に一致するものをすべて見つけるにはどうすればいいですか? 質問する

re.search()テキスト ブロック内の一致を検索する関数を使用すると、テキスト ブロック内で最初の一致が見つかるとプログラムは終了します。

すべての一致が見つかるまでプログラムが停止しないように、これを繰り返し実行するにはどうすればよいですか? これを実行する別の関数はありますか?

ベストアンサー1

re.findall代わりにまたは を使用してくださいre.finditer

re.findall(pattern, string)一致する文字列のリストを返します。

re.finditer(pattern, string)イテレータを返すMatchObjectオブジェクト。

例:

re.findall( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')
# Output: ['cats', 'dogs']

[x.group() for x in re.finditer( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')]
# Output: ['all cats are', 'all dogs are']

おすすめ記事