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: match string where n number of alphabets mandatory and optional numerics and underscore

I am trying to validate a username field like this:

  1. 6 alphabets mandatory
  2. Might contain any number of numericals
  3. Might contain any number of underscores

For example: abcdef, abc9def, _testaa, __test_aa_, hello_h_9, _9helloa, 9a8v6f_aaa
All these should match, that is, the number of alphabets should be more than n numbers (here 6) in the whole string, and _ and numerics can be present anywhere.

I have this regex: [\d\_]*[a-zA-Z]{6,}[\d\_]*
It matches strings like: _965hellof
But doesn’t match strings like: ede_96hek

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

I also have tried this regex: ^(?:_?)(?:[a-z0-9]?)[a-z]{6,}(?:_?)(?:[a-z0-9])*$
Even this fails to match.

>Solution :

You need to use a lookahead like this:

/^(?=[^A-Za-z]*([A-Za-z][^A-Za-z]*){6}$)\w+$/

This is in two parts, the long part verifies there are exactly 6 alphabetic characters present without moving the scanners cursor position. Then the \w+ says all the characters must be alphanumeric or underscore. The ^ & $ ensure the entire string conforms.

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