<p>使用下面这样的负展望。</p>
<pre><code>>>> s = "cat goose mouse horse pig cat cow"
>>> re.sub(r'^((?:(?!cat).)*cat(?:(?!cat).)*)cat', r'\1Bull', s)
'cat goose mouse horse pig Bull cow'
</code></pre>
<p><a href="https://regex101.com/r/sS1qO8/4" rel="nofollow noreferrer">DEMO</a></p>
<ul>
<li><code>^</code>断言我们已经开始了。</li>
<li><code>(?:(?!cat).)*</code>匹配任何字符,但不匹配<code>cat</code>,零次或多次。</li>
<li><code>cat</code>匹配第一个<code>cat</code>子字符串。</li>
<li><code>(?:(?!cat).)*</code>匹配任何字符,但不匹配<code>cat</code>,零次或多次。</li>
<li>现在,将所有模式封装在一个捕获组(如<code>((?:(?!cat).)*cat(?:(?!cat).)*)</code>)中,以便我们以后可以引用这些捕获的字符。</li>
<li><code>cat</code>下面的第二个<code>cat</code>字符串匹配。</li>
</ul>
<p><strong>或</strong></p>
<pre><code>>>> s = "cat goose mouse horse pig cat cow"
>>> re.sub(r'^(.*?(cat.*?){1})cat', r'\1Bull', s)
'cat goose mouse horse pig Bull cow'
</code></pre>
<p>更改<code>{}</code>中的数字,以替换字符串<code>cat</code>的第一个或第二个或第n个匹配项</p>
<p>要替换第三个出现的字符串<code>cat</code>,请将<code>2</code>放在大括号中。。</p>
<pre><code>>>> re.sub(r'^(.*?(cat.*?){2})cat', r'\1Bull', "cat goose mouse horse pig cat foo cat cow")
'cat goose mouse horse pig cat foo Bull cow'
</code></pre>
<p><a href="https://regex101.com/r/wP7pR2/52" rel="nofollow noreferrer">Play with the above regex on here ...</a></p>