壊滅的なバックトラッキングを回避し、任意の量の中断を許可するソリューションがいくつかあります!
ソリューション A
これは最もクリーンなソリューションですが、正規表現モジュールが必要です (win binaries here )。(?>...)
バックトラッキングを避けるために、アトミック グループ を使用します。
import regex
strExampleFile = '''United Nations & Headquarters
United <br> Nations Headquarters
United Natio<b>ns Hea</b>dquarters'''
strSearch = 'United Nations Headquarters'
strRegex = regex.sub(r'((?<!^).)',r'(?>[\s\S]*?(?=\1))\1',strSearch)
rexRegex = regex.compile(strRegex)
print([objMatch.span() for objMatch in rexRegex.finditer(strExampleFile)])
ソリューション B
正規表現モジュールをインストールしていない、またはインストールしたくない場合は、reを使用してアトミック グループ化を模倣できます。ただし、検索文字列は最大 100 文字に制限されています。
import re
strExampleFile = '''United Nations & Headquarters
United <br> Nations Headquarters
United Natio<b>ns Hea</b>dquarters'''
strSearch = 'United Nations Headquarters'
strRegex = re.sub(r'((?<!^).)',r'(?=([\s\S]*?(?=\1)))\\##\1',strSearch)
for numBackReference in range(1,len(strSearch)) :
strRegex = strRegex.replace("##", str(numBackReference),1)
rexRegex = re.compile(strRegex)
print([objMatch.span() for objMatch in rexRegex.finditer(strExampleFile)])
注: femtoRgon が指摘したように、これらのメソッドはどちらも誤検知を返す可能性があります。