7

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Kev
  • 2,656
  • 3
  • 39
  • 63

4 Answers4

17

How do I count the number of occurences of any characters from a set?

var count = password.Count(nonAlphaNumericCharSet.Contains);
I4V
  • 34,891
  • 6
  • 67
  • 79
1

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 == '!');
Mogli
  • 1,972
  • 11
  • 34
  • 67
1

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();
}
Carra
  • 17,808
  • 7
  • 62
  • 75
1

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

giammin
  • 18,620
  • 8
  • 71
  • 89
  • Thanks. Regexs are powerful but I'm not very good at them. It's important in this case however, to only match punctuation from a predefined set, not just all punctuation. How would I do that with a regex? – Kev May 22 '13 at 11:26
  • @BlackKnight just updated my answer. I'm not good at regular expression either. I find very usefull this cheatsheet: https://github.com/shadowbq/Cheat-Sheets/blob/master/regex/regular-expressions-cheat-sheet-v2.pdf i have printed it and it is always near my desk! – giammin May 22 '13 at 12:42