Why does /(red|green)/g.exec('red, green, red, green') return ["red", "red"]?

时间:2015-06-30 13:38:43

标签: javascript regex

In my javascript console I typed /(red|green)/g.exec('red, green, red, green')

And it returned an array with two results: ["red", "red"]

Shouldn't it return an array with 4 results? As in: ["red", "green", "red", "green"]?

4 个答案:

答案 0 :(得分:5)

As the comment states you want the string method match:

> 'red, green, red, green'.match(/(red|green)/g)
["red", "green", "red", "green"]

答案 1 :(得分:4)

The exec returns only the first match even if you specify g global flag.

The exec() method executes a search for a match in a specified string. Returns a result array, or null.

Because the first element in the array is the complete match string and second element of the array is the capturing group which is enclosed inside () in the regex.

If you try this regex:

/(red|green),/g.exec('red, green, red, green')

You'll get

["red,", "red"]

答案 2 :(得分:1)

The way exec works is by returning an array* of results AND modifying the regex object.
*) returns null if no match found.

The returned array contains the entire matched string at index 0, and 1 entry per matched group.

In your example, the returned result is:
[0] = "red" <-- The entire match
[1] = "red" <-- The match for the first group

For example, the next snippet returns THE SAME RESULT:

alert(JSON.stringify(/(red|green)/g.exec('red, green, red, green, red, green, red, green')))

And the next one returns an array with 3 entries (Whole match, 2 groups):

alert(JSON.stringify(/(red|green), (red|green)/g.exec('red, green, red, green, red, green, red, green')))

答案 3 :(得分:0)

Given the following string and regex

var str = "red, green, red, green";
var re = /(red|green)/g;

With exec()

var m;
while ((m = re.exec(str)) !== null) {
  console.log(m);
}

Output:

["red", "red"]
["green", "green"]
["red", "red"]
["green", "green"]

The returned array has the matched text as the first item, and then one item for each capturing parenthesis

and

If your regular expression uses the "g" flag, you can use the exec() method multiple times to find successive matches in the same string. (ref)


With match()

console.log( str.match(re) );

Output:

["red", "green", "red", "green"]