C# Regex Word Count

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;
            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
C# Regex Word Count, 3.0 out of 5 based on 1 rating

Incoming Search Term

If you are a Linux guy, you will be upset to know that you are required a .NET Passport to login at Adobe and utilize the DRM Activator for your CCDA 640-863. The Microsoft Certified Systems Engineer on Windows Server 2003 diploma 70-293 is designed for IT professionals who work in the characteristically multifaceted computing environment of medium-sized to large businesses. Candidates for 70-536 work on a group in a small or large development environment that employs Microsoft Visual Studio .NET 2003 Enterprise Developer. CompTIA’s A+ 220-602 "IT Technician" test is among those two tests needed to accomplish the A+ 2006 certification.

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 😀