擅长:python、mysql、java
<p>有两个解决方案可以避免灾难性的回溯<em>和</em>允许任何数量的中断!
</p><p><br/>
<strong>解决方案A</strong></p>
<p>这是最干净的解决方案,但需要<a href="http://pypi.python.org/pypi/regex" rel="nofollow">regex</a>模块(win二进制文件<a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#regex" rel="nofollow">here</a>)。它使用原子分组,<code>(?>...)</code>,以避免回溯:</p>
<pre><code>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)])
</code></pre>
<p/><p><p><br/>
<strong>解决方案B</strong></p>
<p>如果您既没有安装也不想安装<a href="http://pypi.python.org/pypi/regex" rel="nofollow">regex</a>模块,那么re<em>可以用来模拟原子分组。但是,搜索字符串现在限制为最多100个字符:</p>
^{pr2}$
<p><strong>注意:</strong>正如femtoRgon所指出的,这两种方法都会返回假阳性。在</p>