Parsing Capital Letters

I found an intersting question on the ASP.NET forums this morning. How can you get a count of the capital letters in a string? My first thought was, 'This is a Job for Regex!'.

If you are not familiar with regular expressions, please get to know them, they are frustrating, fun and very powerful. They provide a way to define a pattern of sorts to parse content from a string, quickly. I use them for many things, such as parsing and reformating phone numbers, filtering profanity, etc. To use regular expressions in .NET you need to create a Regex object. You then need to define a regular expression to match the values or pattern you need. In this case I just need to match capital letters, which is a very simple regex, "[A-Z]". You can find an entire collection of these patterns on

I used the term 'match' for a reason. The RegEx class has a Matches function that returns a MatchCollection or a collection of Matches to the pattern. The MatchCollection object has a Count property, which returns the number of matches in the string. This is the value needed to solve the problem asked on the forum.

Next I decided to go ahead and echo each of the matched capital letters just to make sure that is what was matched. You can choose to ignore case, whitespace and several other options by defining a list of RegexOptions in the constructor of the RegEx. The default is to match case, which is what I needed for this problem.

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Text;

namespace GetCapCount
    class Program
        static void Main(string[] args)

            string crazyString = "This IS a CraZy LOOking sTrinG.";

            Regex rg = new Regex("[A-Z]");
            MatchCollection mc = rg.Matches(crazyString);

            Console.WriteLine("Total Capital Letters: " + mc.Count);

            foreach (Match item in mc)



Go forth and Parse!!

Share This Article With Your Friends!