返回匹配的前瞻组

时间:2018-04-04 11:58:34

标签: javascript regex

美好的一天,

我正在尝试返回给定字符串的3位数组,其中数字为"消耗"在JavaScript中两次:

从字符串"123 456"我希望exec为第一场比赛["1", "12"]返回["2", "23"],依此类推。

我尝试使用这样的前瞻:

let exp = /(\d(?=\d\d))/g;    
let match;

while(match = exp.exec("1234 454")) {
    console.log(match);
}

但是,这仍然只是两位数之前的每个数字。

有人有解决方案吗?我已经搜索过,但我不确定要搜索什么,所以我可能错过了一些东西。

提前谢谢!

1 个答案:

答案 0 :(得分:2)

你需要在这里捕获一个积极的前瞻:

let exp = /(?=((\d)\d))/g;    
let match;
while(match = exp.exec("1234 454")) {
     if (match.index === exp.lastIndex) { // \ 
        exp.lastIndex++;                  // - Prevent infinite loop
    }                                     // /
    console.log([match[1], match[2]]);    // Print the output
}

(?=((\d)\d))模式匹配一​​个位置,后跟2位数(捕获到第1组),第一个被捕获到第2组。