<p>我使用simple函数,它列出所有出现的情况,选择第n个出现的位置,并使用它将原始字符串拆分为两个子字符串。然后它替换第二个子字符串中的第一个匹配项,并将子字符串连接回新字符串:</p>
<pre><code>import re
def replacenth(string, sub, wanted, n)
where = [m.start() for m in re.finditer(sub, string)][n-1]
before = string[:where]
after = string[where:]
after.replace(sub, wanted, 1)
newString = before + after
print newString
</code></pre>
<p>对于这些变量:</p>
<pre><code>string = 'ababababababababab'
sub = 'ab'
wanted = 'CD'
n = 5
</code></pre>
<p>输出:</p>
<pre><code>ababababCDabababab
</code></pre>
<p>注:</p>
<blockquote>
<p>The <code>where</code> variable actually is a list of matches' positions, where you pick up the nth one. But list item index starts with <code>0</code> usually, not with <code>1</code>. Therefore there is a <code>n-1</code> index and <code>n</code> variable is the actual nth substring. My example finds 5th string. If you use <code>n</code> index and want to find 5th position, you'll need <code>n</code> to be <code>4</code>. Which you use usually depends on the function, which generates our <code>n</code>.</p>
<p>This should be the simplest way, but it isn't regex only as you originally wanted.</p>
<p>Sources and some links in addition:</p>
<ul>
<li><code>where</code> construction: <a href="https://stackoverflow.com/questions/4664850/find-all-occurrences-of-a-substring-in-python">Find all occurrences of a substring in Python</a></li>
<li>string splitting: <a href="https://www.daniweb.com/programming/software-development/threads/452362/replace-nth-occurrence-of-any-sub-string-in-a-string" rel="nofollow noreferrer">https://www.daniweb.com/programming/software-development/threads/452362/replace-nth-occurrence-of-any-sub-string-in-a-string</a></li>
<li>similar question: <a href="https://stackoverflow.com/questions/1883980/find-the-nth-occurrence-of-substring-in-a-string">Find the nth occurrence of substring in a string</a></li>
</ul>
</blockquote>