javascript正则表达式的正向前瞻

问题描述 投票:17回答:2

我一直搞乱了正则表达式..我觉得我很难......我看过一个代码:

function myFunction() {
   var str = "Is this all there is";
   var patt1 = /is(?= all)/;
   var result = str.match(patt1);
   document.getElementById("demo").innerHTML = result;
}

当我运行此代码时,它给了我输出is

但是,当我添加像/is(?=there)/它没有输出任何东西。我是正规表达的新手..希望你们可以帮助理解正则表达式中的积极前瞻。我已经按照许多教程它没有帮助我。

希望你们能帮助我。谢谢!

javascript regex
2个回答
26
投票

正则表达式is(?= all)匹配字母is,但只有紧接着后面的字母all

同样,正则表达式is(?=there)匹配字母is,但只有紧接着后面的字母there

如果你把这两个组合在is(?= all)(?=there)中,你试图匹配字母is,但只有当它们同时被字母all和字母there同时紧跟时......这是不可能的。

如果你想匹配字母is,但只有当它们被字母all或字母there紧跟时,你可以使用:

is(?= all|there)

另一方面,如果你想匹配字母is,但只有紧跟着字母all there,那么你可以使用:

is(?= all there)

如果我想让is跟随allthere,但字符串中的任何地方怎么办?

然后你可以使用像is(?=.* all)(?=.*there)这样的东西

理解前瞻的关键

结果的关键是要理解前瞻是一个断言,它检查某些东西是否跟随,或者先于字符串中的特定位置。这就是我立刻加粗的原因。以下文章应该消除任何混淆。

参考

Mastering Lookahead and Lookbehind


8
投票

由于there没有立即遵循的事实,积极的前瞻失败了。

is(?=there) # matches is when immediately followed by there

要匹配的是如果there跟在字符串中的某个位置,你会这样做:

is(?=.*there) 

说明:

is          # 'is'
(?=         # look ahead to see if there is:
  .*        #   any character except \n (0 or more times)
  there     #   'there'
)           # end of look-ahead

Demo

我推荐的详细教程:How to use Lookaheads and Lookbehinds in your Regular Expressions

© www.soinside.com 2019 - 2024. All rights reserved.