Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

regex

I want to check if the user's input in the server side. If the user enters a number 111111 or 22222 which has the same numbers, and also if the input is in sequence like 12345 or 456789.

like image 338
yyy Avatar asked Jul 29 '11 08:07

yyy


2 Answers

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.

like image 63
Susam Pal Avatar answered Oct 23 '22 09:10

Susam Pal


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.

like image 23
drf Avatar answered Oct 23 '22 08:10

drf