Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using lookahead, how to ensure at least 4 alphanumeric chars are included + underscores

I'm trying to make sure that at least 4 alphanumeric characters are included in the input, and that underscores are also allowed.

The regular-expressions tutorial is a bit over my head because it talks about assertions and success/failure if there is a match.

^\w*(?=[a-zA-Z0-9]{4})$

my understanding:

\w --> alphanumeric + underscore

* --> matches the previous token between zero and unlimited times ( so, this means it can be any character that is alphanumeric/underscore, correct?)

(?=[a-zA-Z0-9]{4}) --> looks ahead of the previous characters, and if they include at least 4 alphanumeric characters, then I'm good.

Obviously I'm wrong on this, because regex101 is showing me no matches.

like image 813
avnav99 Avatar asked Sep 29 '21 18:09

avnav99


1 Answers

You want 4 or more alphanumeric characters, surround by any number of underscores (use ^ and $ to ensure it match's the whole input ):

^(_*[a-zA-Z0-9]_*){4,}$
like image 158
HFZ Avatar answered Sep 18 '22 00:09

HFZ