browse by category or date

I notice from my traffic log that there was someone bumping to this blog searching for ‘C# Regex Word Count’. Since I never create such tutorial, so here you go.

The basic rule of a word would be it doesn’t contain any whitespaces (spaces, tabs, or newlines). So the easiest Regex would be:

[^\ ^\t^\n]+

Now to implement it using C#, It would be as follows:

      public int WordCount(String input)
      {
         int result = 0;
         try
         {
            Regex rgx = new Regex(@"[^\\ ^\\t^\\n]+");
            MatchCollection mcMatches = rgx.Matches(input);
            result = mcMatches.Count;            
         }
         catch (Exception ex)
         {
         }
         return result;
      }

An improvement would be putting the Regex creation out of the function, this way we will not re-created the Regex everytime the function is called.

About Hardono

Hi, I'm Hardono. I am working as a Software Developer. I am working mostly in Windows, dealing with .NET, conversing in C#. But I know a bit of Linux, mainly because I need to keep this blog operational. I've been working in Logistics/Transport industry for more than 9 years.

2 comments so far

Add Your Comment
  1. So Dono love regex too. Happy to know. What is your ‘mahdzab’? POSIX, Perl, …? 😀

  2. Hehe … at the moment its C# and/or VB.NET, but I might switch allegiance to Phyton or Ruby for the cool factor 😀