正则表达式,select 最接近的匹配

Regex, select closest match

假设以下词序

BLA text text text  text text text BLA text text text text LOOK text text text BLA text text BLA

我想做的是从BLA中提取文本到LOOK,但是最接近look的BLA。 IE。我想得到

BLA text text text text LOOK 

我应该如何使用正则表达式来做到这一点?我找到了一种可行的解决方案,但效率极低。

BLA(?!.*?BLA.*?LOOK).*?LOOK

是否有更好、更高效的方法来实现匹配此模式?

我想做的是:我想匹配 BLA,然后前瞻,直到使用 LOOK 进行正前瞻或使用 BLA 进行负前瞻。但我不知道如何将其放入正则表达式中。

作为引擎,我在 python.

中使用 re

只查找 LOOK 和 BLA 之间的文本,无需 BLA

In : re.search(r'BLA [^(BLA)]+ LOOK', 'BLA text text text  text text text BLA text text text text LOOK text text text BLA text text BLA').group()
Out: 'BLA text text text text LOOK'

:-)

(?s)BLA(?:(?!BLA).)*?LOOK

试试这个。参见 demo

或者,使用

BLA(?:(?!BLA|LOOK)[\s\S])*LOOK

为了更安全。

另一种提取所需文本的方法是使用 tempered greedy token 技术,该技术匹配一系列不以不需要的字符串开头的单个字符。

r'\bBLA\b(?:(?!\bBLA\b).)*\bLOOK\b'

Start your engine! | Python code

\bBLA\b        : match 'BLA' with word boundaries
(?:            : begin non-capture group
  (?!\bBLA\b)  : negative lookahead asserts following characters are not
                 'BLA' with word boundaries
  .            : match any character
)              : end non-capture group
*              : execute non-capture group 0+ times
\bLOOK\b       : match 'LOOK' with word boundaries

包含单词边界以避免匹配单词,例如 BLACKTRAILBLAZER