RegEx to check if the digits in a number are all the same or in sequence

This pattern will match if the user enters the same digit:

^(\d)\1*$

\1 matches the first capture group, so the pattern matches whether that first digit is repeated for the entire string.

The second problem (consecutive digits) is somewhat more difficult.

^(?:^(?:^(?:^(?:^0?1)?2)?3)4?)?5(?:$|6(?:$|7(?:$|8(?:$|90?))))$|
    ^(0?1)?2(?:$|3(?:$|4))|^(6?7)?8(?:$|90?)$

is one implementation, assuming three or more digits. But since the number of combinations is small, enumerating (4+ digits) is also possible:

^(?:0?123(45?)?|1?23456?|2?34567?|3?45678?|4?56789?|(5?6)?7890?|
         (0?1)?2345678?(90$)?|1?23456789?|2?345678(90?)?)$

All this said, regular expressions don't always work well for this type of problem. A Java method to check for this sequence might be cleaner.


To match consecutive same digits:

^([0-9])\1*$

Note that you have to escape the backslash when you put it in a java string literal, for example,

"^([0-9])\\1*$"

For the second one you have to explicitly make a list of consecutive digits using the | operator. The regex would be really long and nasty with as many as 10-nested parantheses. One has to generate this regex using a program. In other words, this is a wrong problem to solve using regex. It would be much simpler to write a loop and test this.


This time in perl, to explain the second case easier:

perl -nlE 'say "BAD number" if ($_ =~ /^(\d)\1*$/ or "123456789" =~ /$_/)'

Explanation:

  • case 1 : input ∈ /(\d)\1*/ language: already presented ($_ =~ /^(\d)\1*$/)
  • case 2 : string "123456789" matches input ("123456789" =~ /$_/)

Tags:

Java

Regex