Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex 4 non consecutive and no repeated digits

I've been strugling for a few days with this validation. I'm working with Javascript to validate a user pin of 4 digits which shouldn't accept adjacent repeated digits such as 1135 or 1552 etc. It shouldn't accept sequences of digits, for example: 1234 or 3456 or even 1275 (0 sequence digits like 12** *56*, **87, 21** (i.e. no ascending or descending sequence).

I've tried modifying the regex from this answer from @polygenelubricants

His regex is the following:

^(?=\d{4}$)(?:(.)\1*|0?1?2?3?4?5?6?7?8?9?|9?8?7?6?5?4?3?2?1?0?)$

But it also matches 3579 which in my case it should be allowed, so I modified it to be something like this (which in my head means, match all 4 digits numbers, then look for all the digits and check if they're not repeated more than once OR if it doesn't find a 0 and a 1 next to it or a 1 and a 2 next to it... (and the same for descending order))

^(?:\d{4}$)(?:(.)(?!\1)|0?1?|1?2?|2?3?|3?4?|4?5?|5?6?|6?7?|7?8?|8?9?|9?8?|8?7?|7?6?|6?5?|5?4?|4?3?|3?2?|2?1?|1?0?)$

However when I tested it I'm getting all 4 digits numbers but it's not evaluating if they're repeated more than once or are sequenced.

See the running example

like image 445
Frakcool Avatar asked Dec 16 '15 18:12

Frakcool


2 Answers

How about something like this:

(?!.*(?:(\d)\1|12|23|34|45|56|67|78|89|98|87|76|65|54|43|32|21))\d{4}

Tested here: http://www.regexpal.com/?fam=93673

And if 0 needs to be included, do this:

(?!.*(?:(\d)\1|01|12|23|34|45|56|67|78|89|98|87|76|65|54|43|32|21|10))\d{4}
like image 198
Bart Kiers Avatar answered Oct 01 '22 18:10

Bart Kiers


I guess this should do:

/^(?!.*(00|11|22|33|44|55|66|77|88|99|01|12|23|34|45|56|67|78|89|10|21|32|43|54|65|76|87|98))\d{4}$/

https://regex101.com/r/lY7nD4/1

like image 24
Johan Karlsson Avatar answered Oct 01 '22 18:10

Johan Karlsson