Reputation: 945
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
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