正则表达式在ASP.net中的强密码

Hee*_*ers 3 c# regex asp.net passwords

我需要检查包含以下4个中的3个的密码:

  1. 小写字母
  2. 大写字母
  3. 数字字符
  4. 特殊字符(如%,$,#,...)

密码长度必须介于6到20个字符之间.我目前有这个:

public void ChangePassword(string password)
    {

        Regex regex1 = new Regex("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]){6,20}$");
        Regex regex2 = new Regex("^(?=.*[0-9])(?=.*[a-z])(?=.*?[#?!@$%^&*-]){6,20}$");
        Regex regex3 = new Regex("^(?=.*[0-9])(?=.*[A-Z])(?=.*?[#?!@$%^&*-]){6,20}$");
        Regex regex4 = new Regex("^(?=.*[a-z])(?=.*[A-Z])(?=.*?[#?!@$%^&*-]){6,20}$");
        Regex regex5 = new Regex("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*?[#?!@$%^&*-]){6,20}$");

        Match match1 = regex1.Match(password);
        Match match2 = regex2.Match(password);
        Match match3 = regex3.Match(password);
        Match match4 = regex4.Match(password);
        Match match5 = regex5.Match(password);

        if (match1.Success || match2.Success || match3.Success ||
            match4.Success || match5.Success)
        {

            Password = password;

        }
        else
        {
            throw new PasswordNotGoodException();
        }
    }
Run Code Online (Sandbox Code Playgroud)

但是,这根本不匹配.这是一个学校项目,所以我真的可以使用一些帮助.

Hab*_*bib 12

您可以使用以下代替REGEX:

string password = "aA1%";
HashSet<char> specialCharacters = new HashSet<char>() { '%', '$', '#' };
if (password.Any(char.IsLower) && //Lower case 
     password.Any(char.IsUpper) &&
     password.Any(char.IsDigit) &&
     password.Any(specialCharacters.Contains))
{
  //valid password
}
Run Code Online (Sandbox Code Playgroud)

更简单,更干净.

编辑:

如果你需要这4个条件中至少有3个是真的,你可以这样做:

int conditionsCount = 0;
if (password.Any(char.IsLower))
    conditionsCount++;
if (password.Any(char.IsUpper))
    conditionsCount++;
if (password.Any(char.IsDigit))
    conditionsCount++;
if (password.Any(specialCharacters.Contains))
    conditionsCount++;

if (conditionsCount >= 3)
{
    //valid password
}
Run Code Online (Sandbox Code Playgroud)