0

In Javascript ,why

/^(\d{1}){3}$/.exec(123)

returns ["123", "3"], but

/^(\d{1})$/.exec(123)

returns null rather than ["3"].

Also, why is the first expression returning 3, when 1 is the digit that follows ^ ?

MDEV
  • 10,730
  • 2
  • 33
  • 49
尤慕李
  • 425
  • 6
  • 15
  • 5
    Because that's what the regex says. This is ultra basic regex syntax; you should consult a reference, not StackOverflow. – Jon Sep 27 '13 at 10:04
  • 1
    The answer is related to the `^` and `$` anchors... Google it! – sp00m Sep 27 '13 at 10:06
  • Also, `\d{1}` can be simplified to just `\d` - no quantifier means 1 - a quantifier of 1 is therefore pointless – MDEV Sep 27 '13 at 10:07
  • `^` is start of string, `$` is end of string. Meaning first one matches a 3 character string, and captures a single number (because the brackets are only around a single `\d` instead of whole expression). The second rule says the whole string should be a single digit, as the `^` is before it, and `$` after it - hence "123" not matching this one – MDEV Sep 27 '13 at 10:13
  • It doesn't match because you are looking for 1 character only. `^` = starts with `\d` = number `{1}` = maximum 1 `$` = ends with So you are asking for 1 number and nothing else. If you remove either the `^` or `$` or change your quantifier to `{3}` it will work. – Wolph Sep 27 '13 at 10:14
  • 1
    After the edit by Sniffer, this seems worth an answer - it could go on to explain repeated sections of a regex (the `{3}`) and capture groups (why the first regex includes "3" in the results). – Douglas Sep 27 '13 at 10:14
  • 1
    @Douglas The trouble is, it's not asking why the first expression matches 3 instead of 1 - it's just a lack of understanding of regex. This question is easily answered by a number of beginner tutorials around the internet. – MDEV Sep 27 '13 at 10:16
  • 1
    sorry,I'm not good at English, but why 3 also is returned in the first regex , since 3 does not follow ^? – 尤慕李 Sep 27 '13 at 10:24
  • ^ is special char meaning check the fist occurence in a multi char string – Arun Killu Sep 28 '13 at 05:43

1 Answers1

4

First case

Noting that \d{1} is equivalent to just \d,

/^(\d{1}){3}$/

can be simplified to

/^(\d){3}$/

which means

  • begin of the string
  • match a three-digit string
  • end of the string

The parenthesis around \d define a capture group. As explained here and here, when you repeat a capturing group, the usual implementation keeps only the last capture.

That's why the final result is

[
  "123", // the whole matched string
  "3",   // the last captured group
]

Second case

/^(\d{1})$/

can again be simplified to

/^(\d)$/

which means

  • begin of the string
  • match a single digit
  • end of the string

Being 123 a three-digit string, it's not matched by the regex, so the result is null.

Community
  • 1
  • 1
Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235