RegEx to check if the numbers in the number are the same or sequential

I want to check if a user is entered on the server side. If the user enters the number 111111 or 22222, which has the same numbers, as well as if the input is in a sequence similar to 12345 or 456789.

+6
source share
3 answers

To match consecutive identical digits:

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

Note that you need to avoid the backslash when you put it in a java string literal, for example. "^([0-9])\\1*$" .

For the second, you must explicitly make a list of consecutive digits using the | operator . A regular expression would be very long and unpleasant with 10 nested brackets. You need to generate this regular expression using a program. In other words, this is not the right task to solve the problem using regular expressions. It would be much simpler to write a loop and test it.

+11
source

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

 ^(\d)\1*$ 

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

The second problem (consecutive numbers) is somewhat more complicated.

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

- one implementation involving three or more digits. But since the number of combinations is small, it is also possible to enumerate (4 + digits):

 ^(?: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 suggests that regular expressions do not always work well for this type of problem. The Java method for checking this sequence may be cleaner.

+1
source

This time in perl it’s easier to explain the second case:

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

Explanation:

  • case 1: input ∈ /(\d)\1*/ Language: already provided ( $_ =~ /^(\d)\1*$/ )
  • case 2: the string "123456789" matches the input ( "123456789" =~ /$_/ )
+1
source

Source: https://habr.com/ru/post/893847/


All Articles