Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

regex for matching 5 digit numbers, starting with specific digits, but not allowing all repetitions

I will use JavaScript and this is the rules that I need to match:

  • numbers must have exactly 5 digits
  • numbers can only start with 1-4 and 6-9
  • numbers cannot have all digits repeatable

So:

12345  - match
11111  - no match (the same digit is repeated 5x
22220  - match
59876  - no match (starts with the digit 5)
90279  - match
899991 - no match (6 digits)

Here is my exploration of the regex pattern:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

^(?!(\d)\1{4,})\d{5}$

The problem is that I don’t know how to force it to have the first digit as [1-4,6-9].

Any help would be appreciated.

>Solution :

You can simply add a lookahead for starting with ^[1-46-9], if your pattern works:

(?=^[1-46-9])^(?!(\d)\1{4,})\d{5}$

or you can make the following change:

^(?!(\d)\1{4,})[1-46-9][0-9]{4}$
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading