擅长:python、mysql、java
<p>您可以按步骤替换:</p>
<pre><code>poem='''
If I can stop one heart from breaking,
I shall not live in vain;
If I can ease one life the aching,
Or cool one pain,
Or help one fainting robin
Unto his nest again,
I shall not live in vain.
'''
import re
p2 = re.sub("(?:ai|hi)...","*/*",poem)
p3 = re.sub("ch","Ch",p2)
p4 = re.sub("co","Co",p3)
print(p4)
</code></pre>
<p>输出:</p>
^{pr2}$
<p>唯一有趣的是,围绕着ai | hi的一个非捕获组并没有像我预期的那样工作-ai和hi仍然被替换了。您可能需要将它们更改为:</p>
<pre><code>p = re.sub("ai...","*/*",poem, flags = re.DOTALL)
p2 = re.sub("hi...","*/*",p, flags= re.DOTALL)
p3 = re.sub("ch","Ch",p2)
p4 = re.sub("co","Co",p3)
print(p4)
</code></pre>
<p>输出:</p>
<pre><code>If I can stop one heart from breaking,
I shall not live in v*/*If I can ease one life the ac*/*
Or Cool one p*/*Or help one f*/*ng robin
Unto */*est ag*/*I shall not live in v*/*
</code></pre>
<p>{{cd2}也可以匹配^新行。
没有它,<code>vain;</code>将不匹配。在</p>