Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex password validation

Tags:

java

regex

How would I get this so it would check for 2 or more digits in the String? Invoking matches on the String s.

s.matches("^[a-zA-Z0-9]{8,}$");
like image 993
unleashed Avatar asked Feb 16 '11 23:02

unleashed


1 Answers

This should do it...

^(?=.*[0-9].*[0-9])[a-zA-Z0-9]{8,}$

The only change I made is adding this (?=.*[0-9].*[0-9]) which is a positive lookahead that will try to find the first 2 digits within the password. If it's satisfied, then the regular expression will proceed as usual.

Now, I just thought I'd point out that your regular expression will disallow special characters (punctuation and such). In practice, some people like to enter weird characters like this in their passwords.

So you might consider something more like this...

^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).{8,}$

This will allow special characters while also ensuring at least one capital letter, one lower case letter, and one number exist in the password. This is just an example of a strong password regular expression I wrote awhile back, and you could certainly relax those restrictions a bit if you so desired.

like image 200
Steve Wortham Avatar answered Sep 22 '22 23:09

Steve Wortham