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

5

我需要检查密码是否包含以下四个中的三个要素之一:

  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();
        }
    }

然而,这完全没有任何匹配项。这是一个学校项目,所以我确实需要一些帮助。


可能是 https://dev59.com/K2435IYBdhLWcg3w6EmF?rq=1 的重复问题。 - Sean Duggan
2个回答

15

你可以使用以下替代 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
}

更加简洁、干净。

编辑:

如果你需要至少满足这 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
}

你正在使用“&&”来完成所有四项,而OP只需要其中三项 :-) - Sabuj Hassan
@SabujHassan,嗯,我错过了那部分,但我猜OP可以修复那个逻辑,我的观点是正则表达式可能对此来说有些过度。 - Habib

2

这里的最后一个重复是错误的:

Regex regex1 = new Regex("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]){6,20}$");

请改用以下方法:

Regex regex1 = new Regex("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{6,20}$");
//                                   notice the dot here ___^

而且对于你所有的正则表达式都是一样的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接