Q:

String regex not working

I have the following regex in c sharp to check if supplied password is

more than 10 characters
should have at least one lowercase character
should have at least one Uppercase character
Should have either a number or a special character

Regex.IsMatch(password, "^.*(?=.{10,})(?=.*[0-9]|[@#$%^&+=])(?=.*[a-z])(?=.*[A-Z]).*$")

Why wouldn't the above work?
its taking abcdefgh123 but not abcdefgh&+

A:

Personally I'd do a separate check for the length and then one check for each of the character requirements.  I don't like to use overly complicated regular expressions when things can be done in a more readable manner.
if (password.Length > 10 && 
    Regex.IsMatch(password, "[a-b]") && 
    Regex.IsMatch(password, "[A-Z]") && 
    Regex.IsMatch(password, "[0-9@#$%^&+=]"))
{
    //Valid password
}

A:

The problem is probably in (?=.*[0-9]|[@#$%^&+=]), which means .*[0-9] OR [@#$%^&+=] - it should be .*[0-9@#$%^&+=].
Also, you don't really need .* twice in your regex, and can use .{10,} as the main expression, so this should be the same:

^(?=.*[0-9@#$%^&+=])(?=.*[a-z])(?=.*[A-Z]).{10,}$

