RegExp.exec不返回全局结果 [英] RegExp.exec not returning global results

查看:76
本文介绍了RegExp.exec不返回全局结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据MDC https://developer.mozilla.org/en /JavaScript/Reference/Global_Objects/RegExp/exec 以下代码应记录此正则表达式的每个全局匹配项.

According to MDC https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp/exec the following code should log each of the global matches for this regexp.

var str = "(^|\\+)(1\\+1)($|\\+)";
var regex = new RegExp(str, "g");
var result;
var testString = "1+1+1";
while ((result = regex.exec(testString)) != null)
{
    console.log(result);
}

但是我得到的只是第一个比赛,然后循环结束.任何想法,为什么.

But all I get is the first match and then the loop finishes. Any ideas why.

推荐答案

只有一个匹配项,因为不允许重叠.匹配项是:

There's only one match, since overlapping is not allowed. The match is:

(^|\\+) - ^

(1\\+1) - 1+1

($|\\+) - +

很明显不能再有其他比赛了,因为每场比赛都至少需要1+1,而且只剩下一个.另外,使用正则表达式文字更简单:

It should be clear there can't be another match, since every match requires at least 1+1, and there's only a single 1 left. As a separate note, using a regex literal is simpler:

var regex = /(^|\+)(1\+1)($|\+)/g;

这篇关于RegExp.exec不返回全局结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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