7

我正在编写代码来确定密码是否包含足够的标点符号。

如何计算集合中任何字符的出现次数?

这些方面的东西:

private const string nonAlphaNumericCharSet = "#*!?£$+-^<>[]~()&";
...
public static bool PasswordMeetsStrengthRequirements(string password)
{
    return password.Length >= MINIMUM_PASSWORD_LENGTH && password.NumberOfOccurences(nonAlphaNumericCharSet.ToCharArray()) >= MINIMUM_NONALPHANUMERIC_CHARS;
}

优雅的 linq 解决方案的奖励积分。

4

4 回答 4

17

如何计算集合中任何字符的出现次数?

var count = password.Count(nonAlphaNumericCharSet.Contains);
于 2013-05-22T09:51:56.067 回答
1

你可以这样数

int count = "he!l!l!o".Split('!').Length - 1;

它将返回 3。

使用 linq

int count="he!l!l!o".Count(x => x == '!');
于 2013-05-22T09:51:48.110 回答
1

这是一个例子:

private const string nonAlphaNumericCharSet = "#*!?£$+-^<>[]~()&";

public static bool PasswordMeetsStrengthRequirements(string password)
{
    return password.Count(x => nonAlphaNumericCharSet.Contains(x)) > 2 && password.Length > 1;
}

public static void Main()
{
    PasswordMeetsStrengthRequirements("Test").Dump();
    PasswordMeetsStrengthRequirements("Test#").Dump();
    PasswordMeetsStrengthRequirements("(Test#").Dump();
    PasswordMeetsStrengthRequirements("(Te[st#").Dump();
}
于 2013-05-22T09:58:32.850 回答
1

正则表达式

Regex rgx = new Regex(@"^(?=.*(\W.*){4,}).{8,}$", RegexOptions.Compiled);
bool validPassword = rgx.IsMatch(password);

4=min 不是单词/数字字符

8= 最小密码长度

Linq 可能被认为是优雅的(它不是恕我直言),但性能成本是多少?

------------评论后更新---------------

如果你想匹配一个字符子集,你必须替换\W[]

[]= 字符范围

有些字符必须用\

在你的情况下:[#\*!\?£\$\+-\^\<\>\[\]~\(\)&]

在那里你可以找到一个正则表达式备忘单

于 2013-05-22T10:37:43.353 回答