6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RegExp#exec で複数マッチ

Last updated at Posted at 2012-10-11

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!' ] ]

参考
http://stackoverflow.com/questions/520611/how-can-i-match-multiple-occurrences-with-a-regex-in-javascript-similar-to-phps

6
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?