PeepCode の @creationix の回を見ていて気になったので。
まず、複数マッチさせるには、RegExp が global になっていないといけません。
var regexp = /wow/g;
var target = "wow this is great! wow! wow!"
console.log(regexp.exec(target));
// [ 'wow', index: 0, input: 'wow this is great! wow! wow!' ]
console.log(regexp.exec(target));
// [ 'wow', index: 19, input: 'wow this is great! wow! wow!' ]
console.log(regexp.exec(target));
// [ 'wow', index: 24, input: 'wow this is great! wow! wow!' ]
console.log(regexp.exec(target));
// null
console.log(regexp.exec(target));
// [ 'wow', index: 0, input: 'wow this is great! wow! wow!' ]
というふうに、global になっている RegExp は順番にマッチを返してくれます。これは RegExp#lastIndex に前回のマッチが保存されているため。全てのマッチを返し終わった後は一度 null
を返し、その後また最初のマッチに戻ります。
全部のマッチを集めるには、こんな感じです。
var regexp = /wow/g;
var target = "wow this is great! wow! wow!"
var match; // Make sure not to inject global :-)
var matches = [];
while (match = regexp.exec(target)) {
matches.push(match);
}
console.log(matches);
// [ [ 'wow', index: 0, input: 'wow this is great! wow! wow!' ],
// [ 'wow', index: 19, input: 'wow this is great! wow! wow!' ],
// [ 'wow', index: 24, input: 'wow this is great! wow! wow!' ] ]