我遇到了article,它解释了如何进行密码强度验证。
我遇到了遇到的错误问题。一个错误说明: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
或&&
语句所在的行。
我不明白为什么正则表达式语句没有转换为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;
}
答案 0 :(得分:4)
您需要使用IsMatch
,而不是Match
。 IsMatch
会返回bool
,而Match
会返回Match
对象,该对象会为您提供更多详细信息(已捕获的群组等)
答案 1 :(得分:2)
Regex.Match()返回一个Match对象,而不是一个布尔值。您可能想要检查match.Success属性,即
var result = Regex.Match(...);
if(result.Success)
score++;
答案 2 :(得分:0)
Regex.Match
会返回Match
类型。 See this link for official documentation
您需要将代码更改为:
if(Regex.Match(...).Success) {
...
}
或类似的东西。
答案 3 :(得分:0)
如果您只关心成功,那么只需使用Success
的{{1}}属性:
Match
和
if (Regex.Match(password, @"/\d+/", RegexOptions.ECMAScript).Success)