【问题标题】:Regex for strong password in ASP.netASP.net 中强密码的正则表达式
【发布时间】:2014-04-09 13:36:16
【问题描述】:

我需要检查包含以下 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();
        }
    }

但是,这根本不匹配任何东西。这是一个学校项目,所以我真的需要一些帮助。

【问题讨论】:

标签: c# asp.net regex passwords


【解决方案1】:

您可以使用 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 只需要 4 个中的 3 个 :-)
  • @SabujHassan,嗯,我错过了那部分,但我想 OP 可以修复这个逻辑,我的观点是正则表达式可能是矫枉过正。
【解决方案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 ___^

你所有的正则表达式都是一样的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-16
    • 2010-09-16
    • 1970-01-01
    • 1970-01-01
    • 2016-12-17
    相关资源
    最近更新 更多