擅长:python、mysql、java
<p>将大括号加倍工作,它告诉<code>format</code>将大括号视为普通字符(它将它们转义:<a href="https://stackoverflow.com/questions/5466451/how-can-i-print-literal-curly-brace-characters-in-python-string-and-also-use-fo">How can I print literal curly-brace characters in python string and also use .format on it?</a>):</p>
<pre><code>rx = re.compile(r'''
(?:\b\w+\W+){{5}} # five words before
(?:{})
(?:\W+\w+\b){{5}} # five words thereafter
'''.format("|".join(ankerwords)), re.X)
</code></pre>
<p>或使用旧式<code>%</code>格式:</p>
<pre><code>rx = re.compile(r'''
(?:\b\w+\W+){5} # five words before
(?:%s)
(?:\W+\w+\b){5} # five words thereafter
''' % ("|".join(ankerwords)), re.X)
</code></pre>
<p>在这种情况下,由于<code>{5}</code>是重复的,可能是这样的:</p>
<pre><code>rx = re.compile(r'''
(?:\b\w+\W+){five} # five words before
(?:{expr})
(?:\W+\w+\b){five} # five words thereafter
'''.format(expr="|".join(ankerwords),five="{5}", re.X)
</code></pre>
<p>(这样可以避免将大括号加倍,并允许一次性“参数化”字数)</p>