简体   繁体   中英

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

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.

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" =~ /$_/ )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM