美好的一天,
我正在尝试返回给定字符串的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);
}
但是,这仍然只是两位数之前的每个数字。
有人有解决方案吗?我已经搜索过,但我不确定要搜索什么,所以我可能错过了一些东西。
提前谢谢!
答案 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组。