C# Regular Expression How to Count Words in String

 

Overview of Practical

Doing this practical is a 5 steps procedure, first create a simple c# console application, Import Regex Namespace, create a string with repeated words and another string to search given word, using regex to count number of occurrences of a given word in a given string, displaying output.

Step 1:- Create simple c# application project

The first step is to create a simple c# console application project with a nice name as shown in the below figure. So start Microsoft visual studio, click on new project, select console application and press ok.

Once the project is created you will find some default libraries, namespace (Practical) a class with class name (Program) and an empty method with name "Main" as shown in the below code snippet.

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Practical_6a
{
	class Program
        {
          static void Main(string[] args)
	  {
		///code snippet
          }
	}

}

Step 2:- Import Regex Namespace (Regular Expression)

To use regex in a console application we need to import the namespace of "RegularExpressions" from system namespace. Regex class is available in System.Text namespace or dll or library.So by using System.Text let’s call the "RegularExpressions" namespace.

 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace Practical_6a
{
	class Program
        {
          static void Main(string[] args)
	  {
		///code snippet
          }
	}

}

Step 3:- Take up a string with repeated words

Now let’s declare a string with repeated words and another string to specify that repeated word.

 
      class Program
      {
          static void Main(string[] args)
	    {
		string str = "Hello welcome to welcome my first Hello Welcome Console Application";
            string searchItem = "welcome";          
          }
	}

As you can see from the above code that we have declared a string which is having repeated word "welcome" and in another new string where we have specified that repeated word. After this step now let's move on the next step as follows.In order to count the repeated word in a given string we need to use Regex.

Step 4:- Regex - to count the repeated word in a string

Lets use the regex pattern to count the repeated word in a given string or in any string.

      
      class Program
      {
          static void Main(string[] args)
	    {
		string str = "Hello welcome to welcome my first Hello Welcome Console Application";
            string searchItem = "welcome";
            int count = new Regex(searchItem, RegexOptions.Compiled |                     RegexOptions.IgnoreCase).Matches(str).Count;          
          }
	}

As you see from above code that we used Regex class to count the repeated word in a string and stored counted value in new integer variable "count".

What Regex constructor needs?

Constructor Needs

  1. Regex Pattern

  2. RegexOptions

Regex Pattern

In this pattern we can use any regular expression pattern or any word or character to find or to search from a string.

RegexOptions

This is optional. We can use RegexOptions IgnoreCare, RightToLeft, and Multiline and so on depending on our requirement.

In our above we have used the following as shown below.

RegexOptions.IgnoreCase - Which specifies case-insensitive matching.

RegexOptions.Compiled - Which specifies that the regular expression is compiled to an assembly. This yields faster execution but increases startup time.

 
int count = new Regex(searchItem, RegexOptions.Compiled | RegexOptions.IgnoreCase).Matches(str).Count;

As you see in our above code that to count a repeated word in a given string we have used the "Regex" pattern with searchItem string ("welcome") and RegexOptions.IgnoreCase and  RegexOptions.Compiled. 

Step 5:- Display Output

 Now let’s display matching word count using Console.WriteLine().

Now to display output, we have assigned the regex output value to our new interger variable "count" and we have used that “count” variable in Console.WriteLine() to display output.

 
class Program
{
    static void Main(string[] args)
    {
	string str = "Hello welcome to welcome my first Hello Welcome Console Application";
        string searchItem = "welcome";
        int count = new Regex(searchItem, RegexOptions.Compiled | RegexOptions.IgnoreCase).Matches(str).Count;    
        Console.WriteLine("{0} Matches found.", count);
      
    }
}

Conclusion: In a given string repeated word "welcome" was appearing three times, so by using regex methodology we are able to count repeated “welcome” in a given string and executed program successfully and got the output as 3.

Hey friends, if you have any doubt or query regarding above practical, kindly let me know through your comments. Your valuable comments will help me to grow. If you like this article just share it with your friends and subscribe to my youtube channel.

 

 

:: SHARE THIS POST ::

        
 

More C# Articles To Read Next:

 
Dec
07
2013

What are generic collections in C# using an example?

CLICK TO READ FULL ARTICLE

Views - 32930 |Category - C#

Dec
02
2013

What are generics in C# using an example?

CLICK TO READ FULL ARTICLE

Views - 34478 |Category - C#

Aug
25
2013

Use of string.Format method in C# with an example?

CLICK TO READ FULL ARTICLE

Views - 24921 |Category - C#

Jul
31
2013

What is mixed mode arithmetic expression with an example?

CLICK TO READ FULL ARTICLE

Views - 20825 |Category - C#

Jul
22
2013

What is an event handler and explain how it is designed ?

CLICK TO READ FULL ARTICLE

Views - 6073 |Category - C#

 
Author: Gurunatha Dogi
is a software engineer by profession and founder of Onlinebuff.com, Onlinebuff is a tech blog which covers topics on .NET Fundamentals, Csharp, Asp.Net, PHP, MYSQL, SQL Server, Cell Phones and lots more. Follow me @ and twitter.
Leave a Comment......

All fields marked with * are mandatory

d9amb