负向JavaScript [英] Negative Lookbehind JavaScript

查看:92
本文介绍了负向JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道很多人都发布了类似的问题,但是带有g标志,似乎没有任何"hacks"对我有效()(这意味着他们大部分时间都无法正常工作) . 是的,我想要g标志我创建的正则表达式是:

I know that a lot of people have posted a similar question but with the g flag, none of the "hacks" seem to work for me properly (meaning they don't work most of the time). Yes I want the g flag The regex I've made is:

\~\![A-Za-z]+\ start(?:(?:(?:\(|,)\ ?[\w]+)*?\))\:\{([\S\s]+?)(?:(?<!\\)\}\:end)

在支持负向后看法 时,此方法很好.但是当我用JavaScript做到这一点时.它不支持负面观察.这是问题所在的部分:

This works fine when negative look-behind is supported. But when I do it in JavaScript. It doesn't support negative look behind. Here's the part where the problem lies:

(?:(?<!\\)\}\:end)

应匹配的内容:

\}:end    <- Not this
}:end     <- This
foo}:end  <- This

我尝试过:

  • Javascript: negative lookbehind equivalent?
  • JavaScript negative lookbehind issue

推荐答案

代替使用lookbehind,您可以使用lookahead

Instead using lookbehind you can use lookahead

例如

abcdefg;}hijklmn#}

获得

$1 = `abcdefg;}hijklmn`
$2 = `#}`

使用后向方法,您可以

(.*)(?<!#})(#})

请参阅: DEMO (后向方法)

在这里通过使用负向后看来防止#}重复.

which here prevent a duplication of #} by using negative lookbehind.

另一方面,也可以通过生成前瞻"来实现前瞻方法

On the other hand, lookahead approach is also possible by "spawning lookahead",

让我们考虑示例文本

abcdefg;}hijklmn#}

成为

%a%b%c%d%e%f%g%;%}%h%i%j%k%l%m%n%#}

此处%代表前瞻.

我们如何像这样提前生成?

让我们为示例文本考虑超前方法正则表达式

Let's consider lookahead approach regex for our example text

((?:(?!#}).)*)(#})

请参阅:演示(超前处理)

这里的一个窍门是与.一起产生前瞻性,其中正则表达式((?:(?!#}).)*)可以扩展为

A trick here is spawning lookahead together with . where the regex ((?:(?!#}).)*) can be expanded to

((?!#}).(?!#}).(?!#}).(?!#}).(?!#}).(?!#}).) and so on

这意味着它将检查每个字母以确保您在(.*)中没有#}.

that means it will check for every letters to guarantee you that there is no #} in (.*).

因此,如果将此策略应用于您的正则表达式,您将获得

Thus, if apply this strategy to your regex you will get

\~\![A-Za-z]+\ start(?:(?:(?:\(|,)\ ?[\w]+)*?\))\:\{((?:(?!\}\:end\n)[\S\s])+)(?:\}\:end)

请参阅:演示

这篇关于负向JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆