Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reg expression required for strong password [duplicate]

Could anyone help me with a regex for a password with the following please.

include at least two of the following:

a lowercase letter
a capital letter
a number
a 'special character' (e.g. £, $, &, #)

like image 659
John Banks Avatar asked Mar 01 '13 20:03

John Banks


2 Answers

The following should work:

^(?![a-z]*$|[A-Z]*$|\d*$|[\W_]*$).*$

Example: http://www.rubular.com/r/effCmvehdx

The negative lookahead at the beginning will cause this to fail if the entire string is composed entirely of just one group.

Note that even though this fits your requirements, this is not a very good regex for a strong password. You probably also want a length check and you may want to require at least three of those groups instead of two.

like image 176
Andrew Clark Avatar answered Nov 16 '22 17:11

Andrew Clark


As Keith Thompson said in a comment, I don't think a single regex is worth here.

The following code will do what you want, and I think it is more readable, maintainable and easier to prove the correctness than a single regular expression:

string password = "123abc";
string[] regexes = new[]
    {
        "[a-z]", //any lowercase word
        "[A-Z]", //any uppercase word
        @"\d", //any digit
        @"\W" //special characters (or just [£$&#], adding the characters you want)
    };
bool isValid = regexes.Count(regex => Regex.IsMatch(password, regex)) >= 2; 
like image 39
Oscar Mederos Avatar answered Nov 16 '22 15:11

Oscar Mederos