我正在尝试在以下字符串中进行替换:
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.
'''
要求如下:
*\*
替换接下来的三个字符。在我尝试了以下方法:
^{pr2}$输出:
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 f(ai|hi)*\*ng robin
Unto his nest again,
I shall not live in vain.
print(re.sub(r"ch|co",r"Ch|Co",poem))
输出:
If I can stop one heart from breaking,
I shall not live in vain;
If I can ease one life the aCh|Coing,
Or Ch|Cool one pain,
Or help one fainting robin
Unto his nest again,
I shall not live in vain.
你可以看到输出不符合要求。请帮助我找到正确的正则表达式。在
您可以按步骤替换:
输出:
^{pr2}$唯一有趣的是,围绕着ai | hi的一个非捕获组并没有像我预期的那样工作-ai和hi仍然被替换了。您可能需要将它们更改为:
输出:
{{cd2}也可以匹配^新行。 没有它,
vain;
将不匹配。在第一种方法是从替换的模式中引用捕获的组:
对于第二种情况,可以将函数作为替换传递(请参见the ^{} docs ):
^{pr2}$该输出:
^{pr2}$相关问题 更多 >
编程相关推荐