【问题标题】:Need regex for password requirements需要正则表达式来满足密码要求
【发布时间】:2011-07-24 15:08:48
【问题描述】:

我需要一个正则表达式来测试以下用户的密码:

必须是至少 8 个字母数字格式的字符,不超过 4 个连续数字,密码中没有 id(即不能使用:1234、9876、abcd 或 1234abvc)

我目前正在使用^([a-zA-Z0-9!@#$*%]{8,15})$,效果很好,但不考虑连续字符。我不确定如何将其添加到组合中。

任何帮助都会很棒!

【问题讨论】:

  • 连续数字不超过 4 个?请问,这背后的原因是什么?
  • 您要禁止“12345”、“qwerty”等常见模式吗?

标签: c# regex passwords


【解决方案1】:

使用多个实现特定规则的正则表达式比将它们全部融合到一个字符串中要容易得多。

考虑到这一点,这种正则表达式会导致连续失败:

"[a-zA-Z]{4}"
  or
"\d{4}"

【讨论】:

  • 另外,像这样单独执行它们将允许您根据失败的“规则”给出不同的错误消息。例如,“密码不能包含四个连续的数字”,而不是发出通用的“密码无效”并强制用户找出原因。
【解决方案2】:

我不能代表所有人,但我更愿意看到这个而不是正则表达式:

bool IsAcceptedPassword(string password, string id)
{
    if (password.Contains(id)) {
        return false;
    }

    if (password.Length < 8) {
        return false;
    }

    // Adjust allowed characters here
    const string allowedChars = "abcdefghijklmnopqrstuvwxyz0123456789@#$*%";
    const string restrictRunsOf = "0123456789";
    const int MaxRunLength = 4;

    int currentRunLength = 0;
    foreach(var ch in password) {
        if (allowedChars.IndexOf(ch) == -1) {
            return false;
        }

        if (restrictRunsOf.IndexOf(ch) == -1) {
            currentRunLength = 0;
        }
        else if(++currentRunLength > MaxRunLength) {
            return false;
        }
    }

    return true;
}

如果你想让调用者知道为什么密码不被接受,你可以返回enum 类型或抛出异常。我更喜欢enum 方法。

【讨论】:

    【解决方案3】:

    如果你想用正则表达式解决它,只需添加一个否定的前瞻断言。你可以测试一下here

    ^(?!.*\d{4,}.*)([a-zA-Z0-9!@#$*%]{8,})$
    

    添加的部分(?!.*\d{4,}.*) 不会消耗您的字符串,它只是检查是否连续有 4 个或更多数字,如果是,则为 false。

    为什么要将密码限制为 15 个字符?我在示例中删除了它。

    【讨论】:

    • 糟糕,我看到你也有同样的想法。 +1
    • ^(?!.*?[0-9]{4})[a-zA-Z0-9!@#$*%]{8,15}$ 最终起作用了.要求来自客户,而不是我。
    【解决方案4】:

    使用 (commented) 正则表达式轻松完成:

    if (Regex.IsMatch(subjectString, 
        @"# Password: 8-15 alphanums but no more than 3 consecutive digits.
        \A                       # Anchor to start of string.
        (?!.*?[0-9]{4})          # No more than three consecutive digits.
        [a-zA-Z0-9!@#$*%]{8,15}  # Match from 8 to 15 alphanum chars.
        \Z                       # Anchor to end of string.
        ", 
        RegexOptions.IgnorePatternWhitespace)) {
        // Successful match
    } else {
        // Match attempt failed
    } 
    

    【讨论】:

      猜你喜欢
      • 2020-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多