0

My input string is "ssn".

My regexp is /^(s)(s)?((n)(n)?)?$/

Executing:

var regexp = /^(s)(s)?((n)(n)?)?$/;
var match = regexp.exec("ssn");
console.log(match);

Yields:

[
    "ssn",
    "s",
    "s",
    "n",
    "n",
    null
]

Why is the "n" in "ssn" matched 2 times ?

The desired output is:

[
    "ssn",
    "s",
    "s",
    "n",
    null,
    null
]
PinkTurtle
  • 6,942
  • 3
  • 25
  • 44
  • well you got 5 capture groups. – epascarello Dec 09 '22 at 18:19
  • so you are trying to also match `ssnn` or `snn`? – epascarello Dec 09 '22 at 18:19
  • shoot ur right! (not sarcastic), the 2 n matches are actually the same "n" in the string, thanks. I'll accept answer. – PinkTurtle Dec 09 '22 at 18:20
  • @epascarello "ssnn" also valid yes. these are actually function parameters (by type). – PinkTurtle Dec 09 '22 at 18:21
  • 2
    Answer I would have posted is: You have 5 capture groups so you are seeing the n twice because of the 3rd and 4th (nested) capture group. You can see it more clearly with ```var regexp = /^(1)(2)?(3(4)(5)?)?$/; var match = regexp.exec("12345"); console.log(match);``` or diagram https://regexper.com/#%2F%5E%281%29%282%29%3F%283%284%29%285%29%3F%29%3F%24%2F – epascarello Dec 09 '22 at 18:27
  • @epascarello yes someone closed this question, sorry about that. – PinkTurtle Dec 09 '22 at 19:26

0 Answers0