使用密码强度验证器和正则表达式时很少出错

本文关键字:正则表达式 出错 密码 验证 | 更新日期: 2023-09-27 18:16:48

我看到一篇解释如何进行密码强度验证的文章。

我遇到的错误有问题。一个错误状态是:Cannot implicitly convert type 'System.Text.RegularExpressions.Match' to 'bool'if (Regex.Match(password, @"/'d+/",..线上。

另一个错误说:Operator '&&' cannot be applied to operands of type 'System.Text.RegularExpressions.Match' and 'System.Text.RegularExpressions.Match',这发生在AND&&语句的线上。

我不明白为什么Regex语句不转换为bool类型?第二个问题可能与第一个问题有关。

我该如何解决这个问题?

enum PasswordScore
{
    Blank = 0,
    VeryWeak = 1,
    Weak = 2,
    Medium = 3,
    Strong = 4,
    VeryStrong = 5
}
private static PasswordScore CheckStrength(string password)
{
    int score = 1;
        if (password.Length < 1)
            return PasswordScore.Blank;
        if (password.Length < 4)
            return PasswordScore.VeryWeak;
        if (password.Length >= 8)
        score++;
        if (password.Length >= 12)
            score++;
        if (Regex.Match(password, @"/'d+/", RegexOptions.ECMAScript))
            score++;
        if (Regex.Match(password, @"/[a-z]/", RegexOptions.ECMAScript) &&
            Regex.Match(password, @"/[A-Z]/", RegexOptions.ECMAScript))
            score++;
        if (Regex.Match(password, @"/.[!,@,#,$,%,^,&,*,?,_,~,-,£,(,)]/", 
            RegexOptions.ECMAScript))
            score++;
        return (PasswordScore)score;
}

使用密码强度验证器和正则表达式时很少出错

您需要使用IsMatch,而不是MatchIsMatch返回一个bool,而Match返回一个Match对象,它给你更多的细节(捕获的组等)

Regex.Match()返回一个Match对象,而不是一个布尔值。你可能想检查一下匹配情况。Success属性,即

var result = Regex.Match(...);
if(result.Success)
   score++;

如果你只关心成功,那么就使用MatchSuccess属性:

if (Regex.Match(password, @"/'d+/", RegexOptions.ECMAScript).Success)

:

if (Regex.Match(password, @"/[a-z]/", RegexOptions.ECMAScript).Success && 
    Regex.Match(password, @"/[A-Z]/", RegexOptions.ECMAScript).Success) 

Regex.Match返回Match类型。查看官方文档链接

你想把你的代码改成:

if(Regex.Match(...).Success) {
    ...
} 

或者类似的东西