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

I want to write regex that starts and end with numbers and letters only but can have special character hyphen, underscore and space in between

I tried writing this: ^[A-Za-z0-9-][A-Za-z0-9- ]{1,30}$
But the regex should not start and end with a special character or space.

Sample values It should allow:

EcoLight

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

Eco-Light

Eco_Light

Eco Light

Eco Light 1

>Solution :

One option would be to use:

^(?!.{31})[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$

See an online demo. The negative lookahead will prevent over 30 characters while the non-capture group allows for multiple groups of characters that are delimited through any of the characters in the class [ _-].

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