Prasad
Prasad

Reputation: 1600

Regular expression for Avoiding equal ,Consecutive numbers

i am trying to build for the following criteria

     The following captures should not be allowed:

       1) Null fields
       2) Field captured as “000000”
       3) Field captured with consecutive numbers “123456”
       4) Field captured with equal numbers  “111111”
       5) input length is 7 digits not less or more 

Regex Used = ^(?!([0-9]{7})).$

Examples:- 

1111111 1234567 456789 0000000 we invalid successfully 

VALID like 8563241 5342861 all the valid scenarios are also not working .
Could any one help me how to capture valid scenarios with a regular expression .

Thanks, Prasad

Upvotes: 0

Views: 865

Answers (1)

JvdV
JvdV

Reputation: 75840

After some chat we accomplished the following rules, where input:

  • Must be exactly 7 digits.
  • Can't contain any three of the same repetitive characters, e.g: "111".
  • Can't contain any three consecutive numbers (forward/reversed), e.g: "123" or "321".

Therefor, it seems the following does tick your boxes:

^(?!.*?(?:012|123|234|345|456|567|678|789|987|876|765|654|543|432|321|210|(\d)\1\1))\d{7}$

See the online demo

  • ^ - Start string anchor.
  • (?! - Open negative lookahead:
    • .*? - 0+ characters (lazy).
    • (?: - Open non-capture group:
      • 012|123|234|345|456|567|678|789|987|876|765|654|543|432|321|210 - All the alternatives to avoid anywhere in your input.
    • | - Or:
    • (\d)\1\1 - A single digit captured with two backreferences to the same group.
    • )) - Close non-capture group and negative lookahead.
  • \d{7} - 7 Digits.
  • $ - End string anchor.

Upvotes: 1

Related Questions