【问题标题】:Python Regex Variable Negative LookbehindPython正则表达式变量负向后看
【发布时间】:2014-10-15 09:08:14
【问题描述】:

我试图找出前面没有另一组术语的各种术语的出现。通常,如果我在前一组中有一个术语,我可以使用否定的lookbehind,但在 Python 有一个零宽度假设,这似乎不是这种情况。我看到的唯一解决方案是运行两个正则表达式,一个用于存在我正在寻找的内容,另一个用于确认不存在前面的组项。必须有一种更优雅、更有效的方法来做到这一点。有人可以帮忙吗?

测试句是:

10 day trip excludes flights

由于“航班”一词前面带有“排除”,因此确保它不匹配的正则表达式如下:

(?:without|not including|doesn\'?t include|exclud(?:es|ing))\s*(?:flights?(?:\s+tickets)?|airfare|airline tickets?)

但我想确保包含某些文本。我可以通过以下方式确认这一点:

(?:flights?(?:\s+tickets)?|airfare|airline tickets?)

所以这将匹配“包括机票”和“和机票”,但不匹配“没有机票

匹配字符串的一些例子是:

including flights
includes flights
plus flights
flights are included
including airfare
and airfare

不匹配字符串的一些例子是:

not including flights
flights are not included
excluding flights
without airfare

【问题讨论】:

标签: python regex regex-negation


【解决方案1】:

你可以试试下面的正则表达式,

^(?=.*?(?:flights|airfare))(?:(?!without|not includ(?:ing|ed)|doesn\'?t include|exclud(?:es|ing)).)*$

DEMO

【讨论】:

  • 太棒了,没想到用前瞻。
猜你喜欢
  • 1970-01-01
  • 2016-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多