问题描述
假设以下单词序列
BLA text text text text text text BLA text text text text LOOK text text text BLA text text BLA
我想做的是从 BLA 中提取文本到 LOOK,但最接近的 BLA.IE.我想得到
What I would like to do is to extract the text from BLA to LOOK, but the BLA which is the closest to look. I.e. I would like to get
BLA text text text text LOOK
我应该如何使用正则表达式做到这一点?我得到了一种有效的解决方案,但效率极低.
How should I do that using regular expressions? I got one solution which works, but which is exteremely inefficient.
BLA(?!.*?BLA.*?LOOK).*?LOOK
是否有更好、更高效的方法来实现匹配此模式?
Is there a better and more performant way to achieve matching this pattern?
我想做的是:我想匹配 BLA,然后前瞻,直到使用 LOOK 进行正向前瞻或使用 BLA 进行负向前瞻.但我不知道如何将其放入正则表达式中.
What I would like to do is: I would like to match BLA, then forward lookahead until either positive fordward lookahead with LOOK or negative lookahead with BLA. But I don't know a way to put this into a regular expression.
作为引擎,我在 python 中使用 re.
As a engine I use re in python.
推荐答案
(?s)BLA(?:(?!BLA).)*?LOOK
试试这个.请参阅演示.
或者,使用
BLA(?:(?!BLA|LOOK)[\s\S])*LOOK
为了更安全.
这篇关于正则表达式,选择最接近的匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!