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. £, $, &, #)
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With