I'm writing code to determine whether a password contains enough punctuation characters.
How do I count the number of occurrences of any characters from a set?
Something along these lines:
private const string nonAlphaNumericCharSet = "#*!?£$+-^<>[]~()&";
...
public static bool PasswordMeetsStrengthRequirements(string password)
{
return password.Length >= MINIMUM_PASSWORD_LENGTH && password.NumberOfOccurences(nonAlphaNumericCharSet.ToCharArray()) >= MINIMUM_NONALPHANUMERIC_CHARS;
}
Bonus points for an elegant linq solution.
How do I count the number of occurences of any characters from a set?
var count = password.Count(nonAlphaNumericCharSet.Contains);
you can count like this
int count = "he!l!l!o".Split('!').Length - 1;
it will return 3.
Using linq
int count="he!l!l!o".Count(x => x == '!');
Here's an example:
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();
}
what about a RegExp
Regex rgx = new Regex(@"^(?=.*(\W.*){4,}).{8,}$", RegexOptions.Compiled);
bool validPassword = rgx.IsMatch(password);
4=min not word/digit char
8= min password leght
Linq may be considered elegant (it isn't IMHO) but at which performance cost?
------------Update after comment---------------
if you want to match a subset of chars you have to replace \W
with []
[]
= range of chars
some chars have to be escaped with \
in your case: [#\*!\?£\$\+-\^\<\>\[\]~\(\)&]
there you can find a regular expression cheat sheet
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With