Regular Expressions: Count the occurences of characters set/group in a string
Sep 24 2009
Let’s say, you would like to count the number of characters group, for example: all upper case chars in string. How to do it? That’s easy by regular expressions.
Pattern for all upper case chars will be just: [A-Z] So here is a code:
string text = "Hmm, how to count ALL UpperCase chars?"; int result = Regex.Matches(text, "[A-Z]").Count; // result = 6
We can use of course multiple rules at once. For example, to count all occurences of UpperCase chars, digits and 2 special symbols “#?”
string text = "#Hmm#, how to count ALL UpperCase chars?"; // pattern [A-Z] for UpperCase, [0-9] for numeric, [#?] for our special symbols string pattern = @"[A-Z0-9#?]"; int result = Regex.Matches(text, pattern).Count; // result = 9
and another trivial example.. Count all comma in a string.
string text = "1, 2, or maybe 3?"; string pattern = @"[,]"; int result = Regex.Matches(text, pattern).Count; // result = 2


