Why capturing group results in double matches regex

后端 未结 2 1368
暖寄归人
暖寄归人 2020-12-11 08:05

Consider these two scripts:

1st: \" \".match(/(\\s)/)

and

2nd: \" \".match(/\\s/)

Results

1st: [\" \"

2条回答
  •  轮回少年
    2020-12-11 08:44

    Capturing groups serve two purposes. They can be referred later in the regexp (or in the replacement string when using .replace()), but they are also returned by the matching function so they can be used by the caller. This is why .match() returns an array: result[0] is the match for the whole regexp, result[n] is the match for the nth capture group.

    string.split splices the matches for capture groups into the resulting array. The documentation says:

    If separator is a regular expression that contains capturing parentheses, then each time separator is matched the results (including any undefined results) of the capturing parentheses are spliced into the output array. However, not all browsers support this capability.

提交回复
热议问题