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.

GD Star Rating
loading...
C# Regex Word Count, 3.0 out of 5 based on 1 rating

Possibly relevant:

About Hardono

Howdy! 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 11 years.

Incoming Search

algorithm, c#

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 😀