javascript正则表达式的正向前瞻 [英] Positive lookahead with javascript regex

查看:359
本文介绍了javascript正则表达式的正向前瞻的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直搞乱了正则表达式..我发现我很难......我见过这样的代码:

I have been messed up with regex.. I found it difficult for me..I have seen a code like:

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

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

When i run this code it gave me the output is.

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

But when i add like /is(?=there)/ it didnt output anything. I am new to regular expression ..hope you guys can help in in understanding positive lookahead in regex..I have followed many tutorials it didnt helped me.

希望你们这些人可以帮助我。谢谢!

Hope you guys can help me out. Thanks!

推荐答案

正则表达式是(?= all)匹配字母,但前提是立即后跟字母所有

The regex is(?= all) matches the letters is, but only if they are immediately followed by the letters all

同样,正则表达式是(?=那里)匹配字母,但前提是立即后跟字母

Likewise, the regex is(?=there) matches the letters is, but only if they are immediately followed by the letters there

如果你在中合并两个是(?= all)(?=那里),你试图匹配字母,但只有当他们立即后跟字母所有 AND 字母那时 ... 这是不可能的。

If you combined the two in is(?= all)(?=there), you are trying to match the letters is, but only if they are immediately followed both by the letters all AND the letters there at the same time... which is not possible.

如果你想匹配字母,但前提是立即 后面的字母全部 字母那里,然后你可以使用:

If you want to match the letters is, but only if they are immediately followed either by the letters all or the letters there, then you can use:

是(?=所有|那里)

另一方面,如果您希望匹配字母,但前提是立即后跟字母所有那里,然后你可以使用:

If, on the other hand, you want to match the letters is, but only if they are immediately followed by the letters all there, then you can just use:

是(?=所有那里)

如果我想要 后面跟所有那里,但字符串中的任何地方?

What if I want is to be followed by all and there, but anywhere in the string?

然后你可以使用类似的东西(?=。* all)(?=。*那里)

理解前瞻的关键

了解前瞻的关键是要了解前瞻是一个断言,它会检查某些内容是否在在字符串中的特定位置。这就是为什么我立即加强 。以下文章应该消除任何混淆。

The key to lookarounds is to understand that the lookahead is an assertion that checks that something follows, or precedes at a specific position in the string. That is why I bolded immediately. The following article should dispel any confusion.

参考

掌握前瞻和后视

这篇关于javascript正则表达式的正向前瞻的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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