これは別の解決策です。内部テキストバッファを使用して、ファイル全体をメモリにロードせずに、見つかった一致を徐々に生成します。
このバッファは、ファイルテキストを「スライドするウィンドウ」のように機能し、見つかった一致を生成しながら前進します。
ファイルの内容はチャンクによってロードされるため、これは、このソリューションが複数行の正規表現でも機能することを意味します。
def find_chunked(fileobj, regex, *, chunk_size=4096):
buffer = ""
while 1:
text = fileobj.read(chunk_size)
buffer += text
matches = list(regex.finditer(buffer))
# End of file, search through remaining final buffer and exit
if not text:
yield from matches
break
# Yield found matches except the last one which is maybe
# incomplete because of the chunk cut (think about '.*')
if len(matches) > 1:
end = matches[-2].end()
buffer = buffer[end:]
yield from matches[:-1]
ただし、一致するものがまったく見つからない場合は、ファイル全体がメモリに読み込まれる可能性があるため、ファイルに正規表現パターンが何度も含まれていると確信できる場合は、この関数を使用することをお勧めします。