【问题标题】:Lookarounds with lazy quantifiers带有惰性量词的环顾四周
【发布时间】:2021-07-06 13:07:59
【问题描述】:

我正在尝试在正则表达式中使用后视后跟一个懒惰的“匹配所有模式”(.+?),但我想知道是否可以通过这种方式使用环视。

例如,我有以下正则表达式:(?<!learn).+?write a regex

  • "I'm learning how to write a regex" (不应匹配)
  • "I know how to write a regex" (应该匹配)
  • "I know how to read an write a regex" (应该匹配)
  • "I want to know how to write a regex" (应该匹配)
  • "I want to learn how to write a regex" (不应匹配)

如果你使用上面的正则表达式,你会得到所有匹配的东西。

【问题讨论】:

  • 一切都匹配,因为正则表达式在 write a regex 左侧找到与 learn 不匹配的任何字符串。因此,在您的第一个示例中,I'm l 与 learn 不匹配,因此负后向为 TRUE,然后 earning how to 匹配 .+?n,write a regex 匹配结束。
  • 是的,我就是这么想的...所以我不能使用lookbehind后跟FIND ANY模式:/
  • 我不知道如何简单地说“包含 X,但不包含 Y”。当然在 Python 中你可以测试同一个字符串两次...
  • 可以使用在开头锚定的负前瞻 ^(?!.*learn).*write a regex 可以使用,否则另一种解决方案是首先匹配不想要的模式:(learn.*write a regex)|write a regex 并执行 no-op if第一组被捕获。由于回溯的工作原理,替代部分是按顺序检查的
  • @Chris Maurer 是的,我做到了,但是以这种方式衡量我的正则表达式的精度真的很痛苦......

标签: python-3.x regex regex-lookarounds


【解决方案1】:

您的模式匹配所有行,因为(?<!learn).+?write a regex 将在第一个位置运行lookbehind,断言当前位置直接左侧的不是learn

断言为真,这部分将立即匹配,直到第一次出现write a regex

您可以做的是使用PyPi regex module,它支持在后视中无限量词:

(?<!\blearn.+?)\bwrite a regex\b

Regex demo | Python demo

import regex

pattern = r"(?<!\blearn.+?)\bwrite a regex\b"

strings = [
    "I'm learning how to write a regex",
    "I know how to write a regex",
    "I know how to read an write a regex",
    "I want to know how to write a regex",
    "I want to learn how to write a regex"
]

for s in strings:
    if regex.search(pattern, s):
        print(s)

输出

I know how to write a regex
I know how to read an write a regex
I want to know how to write a regex

【讨论】:

  • 谢谢,我不知道这个包,这很有帮助!我查看了文档,但我不太确定是否也可以在环视中使用条件运算符。我正在考虑类似的事情:r"(?&lt;!\blearn|want.+?)\bwrite a regex\b"
  • @RomainM 你的意思是这样吗? (?&lt;!\b(?:learn|want).+?)\bwrite a regex\b regex101.com/r/2cf7eq/1 如果.*? 应该适用于两个词,则应该对交替进行分组。
  • 是的,确切地说,我想知道为什么不分组条件模式就不能工作,哈哈……非常感谢!
猜你喜欢
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 2011-01-25
  • 1970-01-01
  • 1970-01-01
  • 2015-07-09
  • 2023-03-13
相关资源
最近更新 更多