开发者

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜