【问题标题】:I'm trying to perform certain pattern matching using python's re module我正在尝试使用 python 的 re 模块执行某些模式匹配
【发布时间】:2018-12-13 20:40:58
【问题描述】:
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."

问题:

如果模式中有字符aihi,则将接下来的三个字符替换为*\*

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

预期输出:

如果我能阻止一颗心碎,

我不会白活的;

如果我可以让一个人的生活变得更轻松*\*

或冷却一种疼痛,

或者帮助一个fai*\*ng robin

再次嗨*\*est,

我不会白活。

我的代码:

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

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

【问题讨论】:

  • 你有没有尝试过?
  • 我有,但我能做的就是找到ai
  • 您说的是 3 个字符,但预期的输出只显示 2。是 2 还是 3?
  • 对不起,我已经编辑了问题
  • 这对你有用吗:jdoodle.com/embed/v0/QOe

标签: python regex pattern-matching


【解决方案1】:

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

说明

(?&lt;=[ah]i)是正向lookbehind,只有前两个字符匹配[ah]i模式时才会匹配

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

【讨论】:

  • 这段代码完美运行,这里的 ?
  • @vishalborana 这是一个积极的看法。通常,正则表达式模式将“消耗”它们匹配的模式,因此您不能再次使用它们。但是,前瞻和后瞻将允许您“窥视”模式而不消耗它regular-expressions.info/lookaround.html
猜你喜欢
  • 2019-06-11
  • 1970-01-01
  • 2018-12-10
  • 2022-01-19
  • 2023-02-07
  • 1970-01-01
  • 2017-01-17
  • 1970-01-01
  • 2011-07-14
相关资源
最近更新 更多