C# Regex (Regular Expression)

In c#, regular expression (regex) is a pattern, and it is useful to parse and validate whether the given input text is matching the defined pattern (such as an email address) or not.

 

Generally, the key part to process the text with regular expressions is the regular expression engine, and it is represented by Regex class in c#. The Regex class is available with System.Text.RegularExpressions namespace.

 

To validate the given input text using regular expressions, the Regex class will expect the following two items of information.

 

  • The regular expression pattern to identity in the text.
  • The input text to parse for the regular expression pattern.

C# Regular Expression Example

Following is the example of validating whether the given text is in proper email format or not using Regex class in c#.

 

using System;
using System.Text.RegularExpressions;

namespace TutlaneExamples
{
    class Program
    {
       static void Main(string[] args)
       {
          string email = "support@tutlane.com";
          var result = Regex.IsMatch(email, @"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");
          Console.Write("Is valid: {0} ", result);
          Console.ReadLine();
       }
    }
}

If you observe the above example, we are validating whether the input string (email) is invalid email format or not using Regex class IsMatch method by sending input string and the regular expression pattern to validate the input text.

 

When you execute the above code, you will get the result as shown below.

 

Is valid: True

This is how the Regex class is useful to validate the input string by sending regular expression patterns based on our requirements.

C# Regex Class Methods

In c#, the Regex class has different methods to perform various operations on the input string. The following table lists various methods of Regex class in c#.

 

MethodDescription
IsMatch It will determine whether the given input string matches with a regular expression pattern or not.
Matches It will return one or more occurrences of text that match the regular expression pattern.
Replace It will replace the text that matches the regular expression pattern.
Split It will split the string into an array of substrings at the positions that match the regular expression pattern.

These Regex class methods are useful to validate, replace, or split the string values using regular expression patterns based on our requirements.

C# Regex Replace String Example

Following is the example of finding the substrings using a regular expression pattern and replace with required values in c#.

 

using System;
using System.Text.RegularExpressions;

namespace TutlaneExamples
{
   class Program
   {
      static void Main(string[] args)
      {
          string str = "Hi,welcome@to-tut#lane.com";
          string result = Regex.Replace(str, "[^a-zA-Z0-9_]+", " ");
          Console.Write("{0} ", result);
          Console.ReadLine();
      }
   }
}

If you observe the above example, we used Regx.Replace method to find and replace all the special characters in a string with space using regular expression pattern ([^a-zA-Z0-9_]+).

 

Here, the regular expression pattern ([^a-zA-Z0-9_]+) will try to match any single character that is not in the defined character group.

 

When you execute the above example, you will get the result as shown below.

 

Hi welcome to tut lane com

C# Regex Find Duplicate Words Example

Generally, while writing the content, we will make common mistakes like duplicating the words. By using a regular expression pattern, we can easily identify duplicate words.

 

Following is the example of identifying the duplicate words in a given string using Regex class methods in c#.

 

using System;
using System.Text.RegularExpressions;

namespace TutlaneExamples
{
    class Program
    {
       static void Main(string[] args)
       {
          string str = "Welcome To to Tutlane.com. Learn c# in in easily";
          MatchCollection collection = Regex.Matches(str, @"\b(\w+?)\s\1\b", RegexOptions.IgnoreCase);
          foreach (Match m in collection)
          {
             Console.WriteLine("{0} (duplicates '{1}') at position {2}", m.Value, m.Groups[1].Value, m.Index);
          }
          Console.ReadLine();
       }
    }
}

If you observe the above example, we used Regx.Matches method to find the duplicated words using regular expression pattern (\b(\w+?)\s\1\b).

 

Here, the regular expression pattern (\b(\w+?)\s\1\b) will perform a case-insensitive search and identify the duplicate words which exist side by side like To to or in in.

 

When we execute the above example, we will get the result as shown below.

 

To to (duplicates 'To') at position 8
in in (duplicates 'in') at position 36

This is how we can use regular expressions in c# to parse and validate the given string based on our requirements.