【问题标题】:Multiple Regex Matches Using Negative Lookbehind使用负向后查找的多个正则表达式匹配
【发布时间】:2016-02-23 14:20:38
【问题描述】:

我有这一段:

"这是包含主控代码的下一段 预算和其他主预算。它也只包含主 预算条款。但只有这个预算才能匹配。但是这个预算 将无法匹配”。

在这里,我试图只匹配单词“budget”的第一次出现,如果它前面有“master”或“other master”,则跳过所有出现的预算。我为此使用了负面的后视技术,并提出了一段在网站https://regex101.com 上运行良好的代码:

p = re.compile(r'((?<!master|master other)\s\bbudget\b)')
test_str = "This is the next paragraph that contains the code for the master budget and the other master budget. Also it contains only the master budget terms. But only this budget should get matched"
re.findall(p, test_str)

但我收到此错误“look-behind requires fixed-width pattern”。有什么办法吗?

【问题讨论】:

标签: python regex


【解决方案1】:

您遇到的错误是因为 Python 中的lookbehinds 应该是固定长度,而(?&lt;!master|master other) 长度是固定的。

自从

(?<!master|master other)

等价于

(?<!master)(?<!master other)

您可以将您的正则表达式更改为:

((?<!master)(?<!master other)\s\bbudget\b)

【讨论】:

  • 谢谢 Maroun,我试试看。
  • 不需要使用外括号。使用match.group(0)match.group() 轻松访问该值。
猜你喜欢
  • 1970-01-01
  • 2015-06-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-29
  • 1970-01-01
  • 2013-06-19
  • 1970-01-01
  • 2011-02-17
相关资源
最近更新 更多