kidman01
kidman01

Reputation: 945

Match a repeating digit (the same one) exactly two times in Javascript with RegEx

I'm currently trying to match a repeating digit and so far I've got this:

pattern = /(\d){2}/

But when I test this pattern with a number of any length >= 2 it will return true. What I want to find is the following: When I test the number 12344 it should return true and if the number is 12345 it should return false. But having a number of 12444 should also return false. I want to find the same digit repeated exactly twice.

EDIT: Thanks to anybody proposing a solution!

Upvotes: 2

Views: 2609

Answers (2)

Aran-Fey
Aran-Fey

Reputation: 43136

For this kind of task you have to use lookarounds and backreferences:

(?:^|(.)(?!\1))(\d)\2(?!\2)

Explanation:

(?:         // match either...
    ^       // start of the string
|           // or...
    (.)     // any character
    (?!\1)  // not followed by the exact same character
)
(\d)        // then, match and capture a digit
\2          // and the same digit a 2nd time
(?!\2)      // and assert the digit doesn't show up a 3rd time

Upvotes: 8

behkod
behkod

Reputation: 2777

/(00|11|22|33|44|55|66|77|88|99)/

Upvotes: 1

Related Questions