C# - 正则表达式未匹配输入字符串

4
我想要为密码进行一些模式匹配,发现了一个关于正则表达式的示例,但是当我输入一个应该被认为是“强”的密码时,却得到了相反的结果。例如,字符串“JlcimYQF+EkHVA*”得分为1,这意味着字符串模式在正则表达式中没有被匹配,但我不确定原因。
以下是代码:
public class PasswordAdvisor
{
    public static PasswordScore CheckStrength(string password)
    {
        int score = 1;

        if (password.Length < 12)
            return PasswordScore.TooShort;
        if (password.Length >= 16)
            score++;
        if (Regex.Match(password, @"/\d+/", RegexOptions.ECMAScript).Success)
            score++;
        if (Regex.Match(password, @"/[a-z]/", RegexOptions.ECMAScript).Success &&
          Regex.Match(password, @"/[A-Z]/", RegexOptions.ECMAScript).Success)
            score++;
        if (Regex.Match(password, @"/.[!,@,#,$,%,^,&,*,?,_,~,-,£,(,)]/", RegexOptions.ECMAScript).Success)
            score++;

        return (PasswordScore)score;
    }
}

声明:

var passwordStrengthScore = PasswordAdvisor.CheckStrength(@"JlcimYQF+EkH*VA");

        Console.WriteLine((int)passwordStrengthScore);

        switch (passwordStrengthScore)
        {
            case PasswordScore.TooShort:
                Console.WriteLine("Password is too short");
                break;
            case PasswordScore.Weak:
                Console.WriteLine("Password is very weak");
                break;
            case PasswordScore.Medium:
                Console.WriteLine("OK password");
                break;
            case PasswordScore.Strong:
                Console.WriteLine("Strong password");
                break;
            case PasswordScore.VeryStrong:
                Console.WriteLine("Very strong password");
                break;
        }

4
移除所有模式中的 / 分隔符。将 @"/.[!,@,#,$,%,^,&,*,?,_,~,-,£,(,)]/" 替换为 @"[!,@#$%^&*?_~£()-]" 以要求其中一个特殊字符。在除 Regex.Match(password, @"\d+", RegexOptions.ECMAScript) 语句之外的所有语句中,可以安全地移除 RegexOptions.ECMAScript 选项。 - Wiktor Stribiżew
好的,我添加了答案以提供更多的见解。 - Wiktor Stribiżew
1个回答

3

您应该从所有模式中删除/分隔符,因为.NET正则表达式是使用字符串字面量定义的,不需要分隔符,而这些/字符是与预期不相符的部分。

您应该将@"/.[!,@,#,$,%,^,&,*,?,_,~,-,£,(,)]/"替换为@"[!,@#$%^&*?_~£()-]",以要求至少有一个这些特殊字符。请注意,在文本类别之间插入未转义的-会创建范围,因此最好将其放在末尾(或转义它)。 注意:我保留了逗号,但由于您将其用作OR运算符,可能应将其完全删除。 OR关系是正向字符类中原子之间的默认关系。

在除Regex.Match(password,@"\ d +”,RegexOptions.ECMAScript)语句之外的所有语句中,您都可以安全地删除RegexOptions.ECMAScript选项,该选项仅影响简写字符类(如\s\d等)。

使用

    if (Regex.Match(password, @"\d+", RegexOptions.ECMAScript).Success)
        score++;
    if (Regex.Match(password, @"[a-z]").Success &&
      Regex.Match(password, @"[A-Z]").Success)
        score++;
    if (Regex.Match(password, @"[!,@#$%^&*?_~£()-]").Success) // check if you need a comma here
        score++;

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