Why capturing group results in double matches regex

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

Consider these two scripts:

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

and

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

Results

1st: [\" \"

2条回答
  •  醉梦人生
    2020-12-11 08:39

    First script: The first result is the whole pattern, the second is the capturing group

    Second script: the only result is the whole pattern.

    Capturing groups are not only to refer later in the pattern, they are displayed in results too.

    When you use a capturing group with split, the capturing group is returned with results and since the separator is supposed to slice the string, it is normal that you obtain ["", " ", ""] as result with
    " " as input string and /(\s)/ as pattern.

    More informations about split.

    When you write " ".match(/(\s)/) the result returned is the first match. This result is unique and contains:

    • the whole match
    • capturing group(s)
    • index of the match
    • input string

    When you write " ".match(/(\s)/g) the result returned is all the matches:

    • whole match 1
    • whole match 2
    • etc.

    (in the present case you have only one match)

    This behaviour is normal. The match method as two different behaviours (with or without /g). It is a kind of two functions in one. For comparison in PHP (or other languages) which doesn't have the g modifier, you have two different functions: preg_match and preg_match_all

提交回复
热议问题