在不修改正则表达式的情况下,您可以将其设置为在每场比赛后的下半场开始时开始匹配,使用.exec https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/RegExp/exec并操纵正则表达式对象的lastIndex
财产。
var string = 'A1B1Y:A1B2Y:A1B3Y:A1B4Z:A1B5Y:A1B6Y:A1B7Y:A1B8Z:A1B9Y:A1B10Y:A1B11Y';
var reg = /A[0-9]+B[0-9]+Y:A[0-9]+B[0-9]+Y/g;
var matches = [], found;
while (found = reg.exec(string)) {
matches.push(found[0]);
reg.lastIndex -= found[0].split(':')[1].length;
}
console.log(matches);
//["A1B1Y:A1B2Y", "A1B2Y:A1B3Y", "A1B5Y:A1B6Y", "A1B6Y:A1B7Y", "A1B9Y:A1B10Y", "A1B10Y:A1B11Y"]
Demo http://jsbin.com/upesek/5/edit
根据 Bergi 的评论,您还可以获取最后一场比赛的索引并将其增加 1,这样它就不会从比赛的下半场开始匹配,而是从每场比赛的第二个字符开始尝试匹配:
reg.lastIndex = found.index+1;
Demo http://jsbin.com/upesek/7/edit
最后的结果是一样的。不过,Bergi 的更新代码较少,性能也稍差faster http://jsperf.com/setting-lastindex-inside-exec-performance. =]