正则表达式在ASP.net强密码 [英] Regex for strong password in ASP.net

查看:147
本文介绍了正则表达式在ASP.net强密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查含有的3口令以下4种:

I need to check for a password containing 3 of the following 4:


  1. 小写字母

  2. 大写字母

  3. 数字字符

  4. 特殊字符(如%,$,#,...)

密码的长度必须6和20个字符之间。目前,我有这样的:

The length of the password has to be between 6 and 20 characters. I currently have this:

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

然而,这并不在所有符合任何东西。这是一所学校的项目,所以我真的可以使用一些帮助。

However, this doesn't match anything at all. It's for a school project, so I really could use some help.

推荐答案

代替正则表达式中可以使用:

Instead of REGEX you can use:

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
}

更简单,干净。

Much simpler and clean.

编辑:

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

If you need at least 3 out of these 4 conditions to be true you can do:

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
}

这篇关于正则表达式在ASP.net强密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆