Skip to main content
 首页 » 编程设计

python之我正在尝试使用 python 的 re 模块执行某些模式匹配

2024年12月31日9rubylouvre

Text = " 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." 

问题:

如果模式有字符 ai 或 hi,将接下来的三个字符替换为 *\*。

我已经多次尝试使用 re.search() 和 re.sub(),但我无法弄清楚替换接下来三个字符的逻辑。

预期输出:

如果我能阻止一颗心 splinter ,

我不会白活;

如果我可以让生活轻松一点*\*

或清凉一痛,

或者帮助一只 fai*\*ng 知更鸟

再见*\*,

我不会白活。

我的代码:

match_res = re.search(r"ai|hi",poem).group() 

我无法提取“hi” 我也无法获得所需的输出

请您参考如下方法:

re如果您使用积极的后视,模块将为此工作:

your_text = "If I can ease one life the aching," 
re.sub("(?<=[ah]i).{3}", "***", your_text) 

输出

'If I can ease one life the achi***' 

解释

(?<=[ah]i)是正向后视,仅当前两个字符匹配模式 [ah]i 时才会匹配

.{3}匹配任意三个字符(换行符除外)