find and solve || findandsolve.com
Please wait.....

Regex (Regular Expression) in C#

In the c# programming language, the Regex class represents the .NET Framework's regular expression engine. It is also known as C# regular expression or C# regexp is a sequence of characters that defines a pattern.

In c# regex can be used to quickly parse large amounts of text to find specific character patterns; to extract, replace, delete, or edit text substrings; and to add the extracted strings to a collection to generate a report.

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


Using regular expressions to validate the given input text, the Regex class will expect the given below 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


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

using System;
using System.Text.RegularExpressions;
namespace FindAndSolve
{
    public class Program
    {
       public static void Main(string[] args)
       {
          string email = "[email protected]";
          var result = Regex.IsMatch(email, @"^[\w-\.][email protected]([\w-]+\.)+[\w-]{2,4}$");
          Console.Write("Is valid: {0} ", result);
          Console.ReadLine();
       }
    }
}


Output


Is valid: True  


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


C# Regex Class Methods


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


MethodDescription
IsMatchDetermine whether the given input string matches with a regular expression pattern or not.
MatchesReturn one or more occurrences of text that match the regular expression pattern.
ReplaceReplace the text that matches the regular expression pattern.
SplitSplit the string into an array of substrings at positions that match the regular expression pattern.



C# Regex Replace String Example


The given following is the example of finding the substrings using a regular expression pattern and replace with required values in c# programming language.


using System;
using System.Text.RegularExpressions;
namespace FindAndSolve
{
   public class Program
   {
      public static void Main(string[] args)
      {
          string objStr = "Hello,[email protected]^find#-and-solve.com";
          string result = Regex.Replace(objStr, "[^a-zA-Z0-9_]+", " ");
          Console.Write("{0} ", result);
          Console.ReadLine();
      }
   }
}


Output

Hello welcome to find and solve com 


If we observe the given above example,  you used Regx.Replace method to find and replace all the special characters in a string with space using regular expression pattern like  ([^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.


C# Regex Find Duplicate Words Example


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.

In the following given example of identifying the duplicate words in a given string using Regex class methods in c# programming language.


using System;
using System.Text.RegularExpressions;
namespace FindAndSolve
{
    public class Program
    {
       public static void Main(string[] args)
       {
          string objStr ="Hi to To findandsolve.com. Learn c# in in easily way";
          MatchCollection collection = Regex.Matches(objStr, @"\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();
       }
    }
}


Output

to To (duplicates 'to') at position 3

in in (duplicates 'in') at position 36