C# 使用正则表达式的密码标准。当前代码不正确

C# 使用正则表达式的密码标准。当前代码不正确,c#,regex,C#,Regex,我有一个密码标准: 最小密码长度为8个字符。密码必须包含以下4个类别中至少3个类别的字符: 英文大写字符(A到Z) 英文小写字符(a到z) 数字(0到9) 非字母数字字符(即标点符号,如@#$%^+) 我正在使用 Regex compareRegex = new Regex(@"^(?=.*[a-z]{1})(?=.*[A-Z]{1}).{7,}$"); Regex numRegex = new Regex(@"[a-zA-Z0-9].{7,}" ); if (compareRegex.IsM

我有一个密码标准:

最小密码长度为8个字符。密码必须包含以下4个类别中至少3个类别的字符:

  • 英文大写字符(A到Z)

  • 英文小写字符(a到z)

  • 数字(0到9)

  • 非字母数字字符(即标点符号,如@#$%^+)

  • 我正在使用

    Regex compareRegex = new Regex(@"^(?=.*[a-z]{1})(?=.*[A-Z]{1}).{7,}$");
    Regex numRegex = new Regex(@"[a-zA-Z0-9].{7,}" );
    
    if (compareRegex.IsMatch(strPassword))
    {
        int count = txtLoginPassword.Text.IndexOfAny(new char[] { '/', '\\', '[', ']', ':', ';', '|', '=', ',', '+', '*', '?', '<', '>', '@', '\"', '!', '#', '$', '%', '^', '&', '(', ')', '_', '-', '~', '`', '.' });
        if (count >= 0)
            return true;
        if (numRegex.IsMatch(strPassword))
            return true;
        else
            return false;
    }
    else if (numRegex.IsMatch(strPassword))
    {
        bool valid = false;
        int count = txtLoginPassword.Text.IndexOfAny(new char[] { '/', '\\', '[', ']', ':', ';', '|', '=', ',', '+', '*', '?', '<', '>', '@', '\"', '!', '#', '$', '%', '^', '&', '(', ')', '_', '-', '~', '`', '.' });
        valid = (count >= 0);
        return valid;
    }
    else
    {
        return false
    }
    
    Regex compareRegex=newregex(@“^(?=.[a-z]{1})(?=.[a-z]{1})。{7,}$”;
    正则表达式numRegex=新正则表达式(@“[a-zA-Z0-9]。{7,}”);
    if(compareRegex.IsMatch(strPassword))
    {
    int count=txtLoginPassword.Text.IndexOfAny(新字符[]{'/'、'\\'、'['、']'、':'、';'、'|'、'='、'、'、'+'、'*'、'?'、'!'、'.'、'\'、'$'、'%'、'^'、'&'、'('、''.'、''.'、'-'、'.'、'.'、'''''''.'、'''''''.'、''''''.'、'''''''.'、''''''''''.'、'、'''''''';
    如果(计数>=0)
    返回true;
    if(numRegex.IsMatch(strPassword))
    返回true;
    其他的
    返回false;
    }
    else if(numRegex.IsMatch(strPassword))
    {
    bool valid=false;
    int count=txtLoginPassword.Text.IndexOfAny(新字符[]{'/'、'\\'、'['、']'、':'、';'、'|'、'='、'、'、'+'、'*'、'?'、'!'、'.'、'\'、'$'、'%'、'^'、'&'、'('、''.'、''.'、'-'、'.'、'.'、'''''''.'、'''''''.'、''''''.'、'''''''.'、''''''''''.'、'、'''''''';
    有效=(计数>=0);
    返回有效;
    }
    其他的
    {
    返回错误
    }
    

    但是它不起作用。请帮我个人的忙。我只是把它分成不同的检查标准

    private static char[] controlCharacters = 
    { 
         '/', '\\', '[', ']', ':', ';', '|', '=', ',', '+', '*', '?', '<', '>', '@', 
         '\"', '!', '#', '$', '%', '^', '&', '(', ')', '_', '-', '~', '`', '.' 
    };
    
    public static bool ValidPassword(string password)
    {
        if (password.Length < 8)
            return false;
        int sets = 0;
        if (Regex.IsMatch(password, "[A-Z]"))
            sets++;
        if (Regex.IsMatch(password, "[a-z]"))
            sets++;
        if (Regex.IsMatch(password, "[0-9]"))
            sets++;
        if (password.IndexOfAny(controlCharacters)>=0)
            sets++;
        return sets > 2;
    } 
    
    私有静态字符[]控制字符=
    { 
    '/', '\\', '[', ']', ':', ';', '|', '=', ',', '+', '*', '?', '', '@', 
    '\"', '!', '#', '$', '%', '^', '&', '(', ')', '_', '-', '~', '`', '.' 
    };
    公共静态bool ValidPassword(字符串密码)
    {
    如果(密码长度<8)
    返回false;
    整数集=0;
    if(Regex.IsMatch(密码“[A-Z]”)
    集合++;
    if(Regex.IsMatch(密码“[a-z]”)
    集合++;
    if(Regex.IsMatch(密码“[0-9]”)
    集合++;
    if(password.IndexOfAny(controlCharacters)>=0)
    集合++;
    返回集>2;
    } 
    
    或者,如果您想要一个不使用正则表达式的优化版本,您可以这样做

    public static bool ValidPassword(string password)
    {
        if (password.Length < 8)
            return false;
        bool[] sets = new bool[4];
        foreach (char c in password)
        {
            if(c >= 'A' && c <= 'Z')
                sets[0] = true;
            else if (c >= 'a' && c <= 'z')
                sets[1] = true;
            else if (c >= '0' && c <= '9')
                sets[2] = true;
            else if (controlCharacters.Contains(c))
                sets[3] = true;
    
            if (sets.Where(b=>b).Count() > 2)
                return true;
        }
    
        return false;
    }
    
    公共静态bool ValidPassword(字符串密码)
    {
    如果(密码长度<8)
    返回false;
    bool[]集=新bool[4];
    foreach(密码中的字符c)
    {
    如果(c>='A'&&c='A'&&c='0'&&c b).Count()>2)
    返回true;
    }
    返回false;
    }
    

    这一个只是循环遍历字符,并跟踪它看到的每种类型,一旦看到每种类型的3个或更多,它将返回true。

    就我个人而言,我只是将其拆分为每个条件的单独检查

    private static char[] controlCharacters = 
    { 
         '/', '\\', '[', ']', ':', ';', '|', '=', ',', '+', '*', '?', '<', '>', '@', 
         '\"', '!', '#', '$', '%', '^', '&', '(', ')', '_', '-', '~', '`', '.' 
    };
    
    public static bool ValidPassword(string password)
    {
        if (password.Length < 8)
            return false;
        int sets = 0;
        if (Regex.IsMatch(password, "[A-Z]"))
            sets++;
        if (Regex.IsMatch(password, "[a-z]"))
            sets++;
        if (Regex.IsMatch(password, "[0-9]"))
            sets++;
        if (password.IndexOfAny(controlCharacters)>=0)
            sets++;
        return sets > 2;
    } 
    
    私有静态字符[]控制字符=
    { 
    '/', '\\', '[', ']', ':', ';', '|', '=', ',', '+', '*', '?', '', '@', 
    '\"', '!', '#', '$', '%', '^', '&', '(', ')', '_', '-', '~', '`', '.' 
    };
    公共静态bool ValidPassword(字符串密码)
    {
    如果(密码长度<8)
    返回false;
    整数集=0;
    if(Regex.IsMatch(密码“[A-Z]”)
    集合++;
    if(Regex.IsMatch(密码“[a-z]”)
    集合++;
    if(Regex.IsMatch(密码“[0-9]”)
    集合++;
    if(password.IndexOfAny(controlCharacters)>=0)
    集合++;
    返回集>2;
    } 
    
    或者,如果您想要一个不使用正则表达式的优化版本,您可以这样做

    public static bool ValidPassword(string password)
    {
        if (password.Length < 8)
            return false;
        bool[] sets = new bool[4];
        foreach (char c in password)
        {
            if(c >= 'A' && c <= 'Z')
                sets[0] = true;
            else if (c >= 'a' && c <= 'z')
                sets[1] = true;
            else if (c >= '0' && c <= '9')
                sets[2] = true;
            else if (controlCharacters.Contains(c))
                sets[3] = true;
    
            if (sets.Where(b=>b).Count() > 2)
                return true;
        }
    
        return false;
    }
    
    公共静态bool ValidPassword(字符串密码)
    {
    如果(密码长度<8)
    返回false;
    bool[]集=新bool[4];
    foreach(密码中的字符c)
    {
    如果(c>='A'&&c='A'&&c='0'&&c b).Count()>2)
    返回true;
    }
    返回false;
    }
    

    这个函数只是循环遍历字符并跟踪它看到的每种类型,一旦看到每种类型的3个或更多个,它将返回true。

    我使用的正则表达式如下所示:

    ^(?=[^\d\].?\d)\w(\w[!@$%]){8,20}
    这允许使用8到20个字符的密码,其中:

    • 必须包含数字字符并选择特殊字符(
      [!@$%]
    • 密码也不能以数字、下划线或特殊字符开头
    • 最后,必须至少包含一个数字
    然而,出于您的目的,我最好不要使用正则表达式,让代码来处理它:分析密码字符串,并在每次从定义集中找到小写字符、大写字符、数字或字符时设置一个int值:如果没有找到,则为0,如果找到,则为1,这样,您只需添加总数,如果总数大于2,则可以允许输入密码

    在c#中,您可以按照以下要求测试函数:

    using System;
    using System.Collections.Generic;
    class Program 
    {
    
        static IEnumerable<string> GetPermutations(string value) 
        {
            if (value.Length == 1) 
            {
                yield return value;
            } 
            else 
            {
                for (int i = 0; i < value.Length; ++i) 
                {
                    string a = value[i].ToString();
                    foreach (string b in GetPermutations(value.Remove(i, 1))) 
                    {
                        yield return a + b;
                    }
                }
            }
        }
    
        static int findCharsInString(string chars, string stringIn)
        {
            foreach (string to_find in GetPermutations(chars)) 
            {
                int i = stringIn.IndexOf(to_find);
                if (i != -1)
                {
                    return 1;
                }
                return 0;
            }
        }
    
    
        static void Main(string[] args) 
        {
            string lowerCase= "abcdefghijklmnopqrstuvwxyz";
            string upperCase= "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            string numChars = "0123456789";
            string allowedSpecials = "@#$%^+()[]";
    
            string password = "MyNotAllowedPassword";
            string validPW  = "1ValidPassword!";
    
            if ((findCharsInString(lowerCase, password) + findCharsInString(lowerCase, password) + findCharsInString(lowerCase, password)  + findCharsInString(lowerCase, password)) <3)
            {
                //do something to say its an INVALID password
                Console.WriteLine("INVALID pw!!");
            }
            else
            {
                //do something to say its a VALID password
                Console.WriteLine("Valid pw!!");
            }
    
            if ((findCharsInString(lowerCase, validPW) + findCharsInString(lowerCase, validPW) + findCharsInString(lowerCase, validPW)  + findCharsInString(lowerCase, validPW)) <3)
            {
                //do something to say its an INVALID password
                Console.WriteLine("INVALID pw!!");
            }
            else
            {
                //do something to say its a VALID password
                Console.WriteLine("Valid pw!!");
            }
        }
    }
    
    使用系统;
    使用System.Collections.Generic;
    班级计划
    {
    静态IEnumerable GetPermutations(字符串值)
    {
    如果(value.Length==1)
    {
    收益回报值;
    } 
    其他的
    {
    对于(int i=0;i