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

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:


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.

Leave a Reply Cancel reply