If my input string is ~!@#$%^&*()_+{}:\"<>?
How do I get the count of each special character using Regex? For example:
Regex.Match
If you want to follow other approach then you can use.
string str = "@123:*&^789'!@#$*()_+=";
int count = 0;
foreach (char c in str)
{
if (!char.IsLetterOrDigit(c.ToString(),0))
{
count++;
}
}
MessageBox.Show(count.ToString());
It's been a while and I needed a similar answer for handling password validation. Pretty much what VITA said, but here was my specific take for others needing it for the same thing:
var pwdSpecialCharacterCount = Regex.Matches(item, "[~!@#$%^&*()_+{}:\"<>?]").Count;
var pwdMinNumericalCharacters = Regex.Matches(item, "[0-9]").Count;
var pwdMinUpperCaseCharacters = Regex.Matches(item, "[A-Z]").Count;
var pwdMinLowerCaseCharacters = Regex.Matches(item, "[a-z]").Count;
Instead of thinking of every special characters and adding them up, do it the other way; count every letters/digits and subtract them from the count.
You can do that with a simple one-liner :
string input = "abc?&;3";
int numberOfSpecialCharacters = input.Length - input.Count(char.IsLetterOrDigit); //Gives 3
Which you can also change to
int numberOfSpecialCharacters = input.Count(c => !char.IsLetterOrDigit(c));
This should be the answer to your question:
Regex.Matches("Little?~ birds! like to@ sing##", "[~!@#$%^&*()_+{}:\"<>?]").Count
Count should return 6 matches, change the sentence to other variable or something else.
You can find more info about regex expressions here: http://www.zytrax.com/tech/web/regex.htm
Best Regards!
Regex is not the best way to do this. here is the Linq
based solution
string chars = "~!@#$%^&*()_+{}:\"<>?";
foreach (var item in chars.Where(x=> !char.IsLetterOrDigit(x)).GroupBy(x => x))
{
Console.WriteLine(string.Format("{0},{1}",item.Key,item.Count()));
}
I understand that you need to count each spl character count. Correct me If am mistaken.
The non-regex way (which sounds much easier) it to make a list of characters you want to check and use Linq to find the count of those characters.
string inputString = "asdf1!%jkl(!*";
List<char> charsToCheckFor = new List<char>() { '!', '@', '#', ..... };
int charCount = inputString.Count(x => charsToCheckFor.Contains(x));
I am making you write in all the characters you need to check for, because you need to figure out what you want.