How to count many specific characters in a string

Basically, I want to count sets of specific characters in a string. In other words, I need to count all the letters and numbers, and nothing more. But I can not find the correct (regular) syntax. Here is what I have ...

public double AlphaNumericCount(string s) { double count = Regex.Matches(s, "[AZ].[az].[0-9]").Count; return count; } 

I look around, but I don’t seem to find anything that allows for more than one character set. Again, I'm not sure about the syntax, maybe it should be "[AZ] / [AZ] / [0-9]" or something. Anywho, come to me - his first day with Regex.

Thanks.

+6
source share
4 answers

Regular Cheats Expression

Expresso Regular Expression Tool

[AZ].[az].[0-9] will match any uppercase letter ( [AZ] ), followed by any character ( . ), Followed by any lowercase letter ( [AZ] ), followed by any character ( . ), then any number ( [0-9] ).

What you want to combine with any letter or number, [A-Za-z0-9] .

+5
source

If regular expressions are not required, there is a simple alternative solution:

 return s.ToCharArray().Count(c => Char.IsNumber(c) || Char.IsLetter(c)); 
+4
source

Try the following:

 ^[a-zA-Z0-9]+$ 

see regexlib.com

+3
source

If you want to avoid regular expressions, you can simply iterate over the characters in the string and check if they are a letter or a number using Char.IsLetterOrDigit .

 public int AlphaNumericCount(string s) { int count = 0; for(int i = 0; i < s.Length; i++) { if(Char.IsLetterOrDigit(s[i])) count++; } return count; } 
+3
source

All Articles