擅长:python、mysql、java
<p>这很棘手。在Python中,替换文本反向引用未参与匹配<a href="http://www.regular-expressions.info/refreplace.html" rel="nofollow">are an error</a>的组,因此我不得不使用<a href="http://www.regular-expressions.info/lookaround.html" rel="nofollow">lookahead assertions</a>构建一个相当复杂的构造,但它似乎通过了所有的测试用例:</p>
<pre><code>result = re.sub("""(?sx)
( # Either match and capture in group 1:
^ # A match beginning at the start of the string
(?:(?!foo).)* # with all characters in the string unless foo intervenes
$ # until the end of the string.
| # OR
(?=foo) # The empty string right before "foo"
) # End of capturing group 1
(?:foo)? # Match foo if it's there, but don't capture it.""",
r"\1bar", subject)
</code></pre>