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 variable length

I am looking for a regex that matches:

Length is between 1 and 10.

The 8th character can be alphanumeric [0-9a-zA-Z] and the rest have to be digits [0-9]

Valid

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

1
123
1234567890
1234567a

Invalid

1a
123456789a
12345678901

I have tried: [0-9]{1,7}[0-9a-zA-Z][0-9]{0,1} but that is failing miserably

>Solution :

You can match either 1-7 digits, or match 7 digits, the 8th one being [0-9a-zA-Z] and optional 2 digits.

^(?:\d{7}[0-9a-zA-Z]\d{0,2}|\d{1,7})$
  • ^ Start of string
  • (?: Non capture group
    • \d{7}[0-9a-zA-Z]\d{0,2} Match 7 digits and one of 0-9a-zA-Z] and 2 optional digits
    • | Or
    • \d{1,7} Match 1-7 digits
  • ) Close non capture group
  • $ End of string

Regex demo

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