【问题标题】:C# - Regex not matching input stringC# - 正则表达式不匹配输入字符串
【发布时间】:2018-06-22 10:49:10
【问题描述】:

我正在寻找对密码进行一些模式匹配,并在 SO 上找到了 regex example,但是当我传递一个应该被视为“强”的密码时,我遇到了相反的情况。例如,字符串“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;
        }

【问题讨论】:

  • 从所有模式中删除 / 分隔符。将 @"/.[!,@,#,$,%,^,&amp;,*,?,_,~,-,£,(,)]/" 替换为 @"[!,@#$%^&amp;*?_~£()-]" 也需要这些特殊字符之一。在除Regex.Match(password, @"\d+", RegexOptions.ECMAScript) 之外的所有语句中,您可以安全地删除RegexOptions.ECMAScript 选项。
  • 好的,我添加了答案以提供更多见解。

标签: c# regex


【解决方案1】:

您应该将所有模式中的/ 定界符删除为.NET regexes are defined with string literals, no delimiters are required,而这些/ 字符是与您期望的不匹配的模式的一部分。

您应该将@"/.[!,@,#,$,%,^,&amp;,*,?,_,~,-,£,(,)]/" 替换为@"[!,@#$%^&amp;*?_~£()-]" 以至少需要这些特殊字符之一。请注意,文字之间的字符类中未转义的 - 创建了一个范围,因此将其放在末尾(或转义)更安全。注意:我将逗号保留在里面,但是由于您将其用作 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++;

【讨论】:

    猜你喜欢
    • 2011-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-05
    • 2013-12-25
    相关资源
    最近更新 更多