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.
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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With