gpt4 book ai didi

c# - ASP.net 中强密码的正则表达式

转载 作者:行者123 更新时间:2023-11-30 13:22:27 26 4
gpt4 key购买 nike

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

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

最佳答案

除了 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
}

关于c# - ASP.net 中强密码的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22232582/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com