0

The regular expression is

'Gogogo now!'.match(/(go)+/i)

the match method without g flag will return all the capturing groups, from my understanding, the expression will return

['Gogogo', 'Go', 'Gogo', 'Gogogo']

but when I execute the expression, its return value is

["Gogogo","go"]

Can anyone explain for me why?

ChenLee
  • 1,371
  • 3
  • 15
  • 33

2 Answers2

1

the match method without g flag will return all the capturing groups

No, that's not true. In Javascript, when a capturing group is repeated, only the last capture is returned. The g flag is irrelevant here. See this answer for more information.

Then why does match() return an array with two elements?

The documentation tells you that the return value is:

An Array whose contents depend on the presence or absence of the global (g) flag, or null if no matches are found.

  • If the g flag is used, all results matching the complete regular expression will be returned, but capturing groups will not.
  • if the g flag is not used, only the first complete match and its related capturing groups are returned. In this case, the returned item will have additional properties as described below.

So, in your example, the returned array contains the following two elements:

  1. The full match.

  2. The last capture that was captured by group #1.

  • What does its related capturing groups mean? – ChenLee Sep 14 '20 at 03:33
  • Well, consider a pattern like `a(b)(c)`. It contains **two capturing groups**. So, when matched against "abc", if the `g` flag is _not_ used, the returned array will include both groups along with the full match (i.e., `['abc', 'b', 'c']`) and if the `g` flag is used, the returned array will only include the full match (i.e., `'abc'`). Your pattern, on the other hand, only has one capturing group (remember, a repeated capturing group only count as one; the last capture). – 41686d6564 stands w. Palestine Sep 14 '20 at 03:39
-1

Here is an explanation and demonstration

https://regex101.com/r/iNntVP/3

Notice this part of the explanation:

A repeated capturing group will only capture the last iteration. Put a capturing group around the repeated group to capture all iterations or use a non-capturing group instead if you're not interested in the data

Your result array contains the Full match (Gogogo) and the last iteration (go)

sdc
  • 2,603
  • 1
  • 27
  • 40