如何使用Python中的正则表达式在字符串中进行以下替换?

2024-06-16 17:26:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试在以下字符串中进行替换:

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.
'''

要求如下:

  1. 如果模式有字符'ai'或'hi',用*\*替换接下来的三个字符。在
  2. 如果一个单词有“ch”或“co”,则将其替换为“ch”或“co”。在

我尝试了以下方法:

^{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.

你可以看到输出不符合要求。请帮助我找到正确的正则表达式。在


Tags: orinfromliveifnotonecan
3条回答

您可以按步骤替换:

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)

输出:

^{pr2}$

唯一有趣的是,围绕着ai | hi的一个非捕获组并没有像我预期的那样工作-ai和hi仍然被替换了。您可能需要将它们更改为:

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)

输出:

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*/*

{{cd2}也可以匹配^新行。 没有它,vain;将不匹配。在

第一种方法是从替换的模式中引用捕获的组:

poem = re.sub(r"(ai|hi)\w{3}", "\g<1>*\*", poem)

对于第二种情况,可以将函数作为替换传递(请参见the ^{} docs):

^{pr2}$
import re
poem = re.sub(r'(ai|hi)(...)', r'\1*\*', poem)
poem = re.sub('ch', 'Ch', poem)
poem = re.sub('co', 'Co', poem)
print(poem)

该输出:

^{pr2}$

相关问题 更多 >