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 ^ ?

9
  • 5
    Because that's what the regex says. This is ultra basic regex syntax; you should consult a reference, not StackOverflow. Commented Sep 27, 2013 at 10:04
  • 1
    The answer is related to the ^ and $ anchors... Google it! Commented Sep 27, 2013 at 10:06
  • 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). Commented Sep 27, 2013 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. Commented Sep 27, 2013 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 ^? Commented Sep 27, 2013 at 10:24

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.