Python Regex变量负lookback

2024-04-26 23:30:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找出出现的各种术语之前没有另一组术语。通常,如果我在前面的组中有一个术语,我可以使用一个负的lookback,但是Python有一个零宽度的假设,这似乎不是事实。我看到的唯一解决方案是运行两个正则表达式,一个用于显示我要查找的内容,另一个用于确认前面的组项不存在。必须有一种更优雅、更有效的方法。有人能帮忙吗?你知道吗

测试句子是:

10 day trip excludes flights

由于单词“flights”前面有“excludes”,因此确保其不匹配的正则表达式如下:

(?: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

Tags: 字符串示例notareticketswithout术语included