10X Sale
kh logo
All Courses
  1. Tutorials
  2. Programming Tutorials

Regular Expressions in C#

Updated on Sep 3, 2025
 
45,997 Views

Regular expressions denote different patterns like literals, constructs, operators etc. that can be matched with the input.

Regex Class

The immutable regular expressions are represented using a Regex Class. Details about the Regex class is given as follows:

Constructors in Regex Class

The different constructors and their description is given as follows:

Constructors

Description

Regex()

This constructor initializes a new instance of the Regex class.

Regex(SerializationInfo, StreamingContext)

This constructor initializes a new instance of the Regex class by using serialized data.

Regex(String)

This constructor initializes a new instance of the Regex class for the specified regular expression

Regex(String, RegexOptions)

This constructor initializes a new instance of the Regex class for the specified regular expression, with options that modify the pattern.

Regex(String, RegexOptions, TimeSpan)

This constructor initializes a new instance of the Regex class for the specified regular expression, with options that modify the pattern and a value that specifies how long a pattern matching method should attempt a match before it times out.

Table: Constructors in Regex Class in C#
Source: MSDN

Fields in Regex Class

The different fields and their description is given as follows:

Fields

Description

capnames

This field is used by a Regex object generated by the CompileToAssembly method.

caps

This field is used by a Regex object generated by the CompileToAssembly method.

capsize

This field is used by a Regex object generated by the CompileToAssembly method.

capslist

This field is used by a Regex object generated by the CompileToAssembly method.

factory

This field is used by a Regex object generated by the CompileToAssembly method.

InfiniteMatchTimeout

This timeout is used by a Regex object generated by the CompileToAssembly method.

internalMatchTimeout

This timeout is the maximum amount of time that can elapse in a pattern-matching operation before the operation times out.

pattern

This field is used by a Regex object generated by the CompileToAssembly method.

roptions

This field is used by a Regex object generated by the CompileToAssembly method.

Table: Fields in Regex Class in C#

Properties in Regex Class

The different properties and their description is given as follows:

Properties

Description

CacheSize

This property gets or sets the maximum number of entries in the current static cache of compiled regular expressions.

CapNames

This property gets or sets a dictionary that maps named capturing groups to their index values.

Caps

This property gets or sets a dictionary that maps numbered capturing groups to their index values.

MatchTimeout

This property gets the time-out interval of the current instance.

Options

This property gets the options that were passed into the Regex constructor.

RightToLeft

This property gets a value that indicates whether the regular expression searches from right to left.

Table: Properties in Regex Class in C#
Source: MSDN

Methods in Regex Class

The different methods and their description is given as follows:

Methods

Description

CompileToAssembly(RegexCompilationInfo[], AssemblyName)

This method compiles one or more specified Regex objects to a named assembly.

Equals(Object)

This method determines whether the specified object is equal to the current object.

Escape(String)

This method escapes a minimal set of characters (\, *, +, ?, |, {, [, (,), ^, $,., #, and white space) by replacing them with their escape codes. This instructs the regular expression engine to interpret these characters literally rather than as metacharacters.

GetGroupNames()

This method returns an array of capturing group names for the regular expression.

GetGroupNumbers()

This method returns an array of capturing group numbers that correspond to group names in an array.

GetHashCode()

This method serves as the default hash function.

GetType()

This method gets the Type of the current instance.

GroupNameFromNumber(Int32)

This method gets the group name that corresponds to the specified group number.

InitializeReferences()

This method is used by a Regex object generated by the CompileToAssembly method.

IsMatch(String)

This method indicates whether the regular expression specified in the Regex constructor finds a match in a specified input string.

IsMatch(String, String, RegexOptions)

This method indicates whether the specified regular expression finds a match in the specified input string, using the specified matching options.

Match(String)

This method searches the specified input string for the first occurrence of the regular expression specified in the Regex constructor.

Match(String, Int32)

This method searches the input string for the first occurrence of a regular expression, beginning at the specified starting position in the string.

Matches(String)

This method searches the specified input string for all occurrences of a regular expression.

Matches(String, Int32)

This method searches the specified input string for all occurrences of a regular expression, beginning at the specified starting position in the string.

MemberwiseClone()

This method creates a shallow copy of the current Object.

Replace(String, MatchEvaluator)

This method replaces all strings that match a specified regular expression with a string returned by a MatchEvaluator delegate.

Replace(String, MatchEvaluator, Int32)

This method replaces a specified maximum number of strings that match a regular expression pattern with a string returned by a MatchEvaluatordelegate.

Split(String)

This method splits an input string into an array of substrings at the positions defined by a regular expression pattern specified in the Regex constructor.

Split(String, Int32)

This method splits an input string a specified maximum number of times into an array of substrings, at the positions defined by a regular expression specified in the Regex constructor.

ToString()

This method returns the regular expression pattern that was passed into the Regexconstructor.

Unescape(String)

This method converts any escaped characters in the input string.

UseOptionC()

This method is used by a Regex object generated by the CompileToAssembly method.

UseOptionR()

This method is used by a Regex object generated by the CompileToAssembly method.

ValidateMatchTimeout(TimeSpan)

This method checks whether a time-out interval is within an acceptable range.

Table: Methods in Regex Class in C#
Source: MSDN

Program 1

A program that displays all the patterns of one or more digits is given as follows:

using System;
using System.Text.RegularExpressions;
class Example
{
   static void Main()
   {
       Regex regex = new Regex(@"\d+");
       MatchCollection match = regex.Matches("The numbers 3 and 5 are prime");
       foreach (Match m in match)
       {
           Console.WriteLine(m);
        }
   }
}

Source Code: Program that displays all the patterns of one or more digits using regular expressions in C#

The output of the above program is as follows:

3
5

Now let us understand the above program.

The Regex class constructor is used in the above program and it uses a pattern that specifies one or more digits. The code snippet for this is given as follows:

Regex regex = new Regex(@"\d+");

Then the matches method is used that specifies all the occurrences of digits in the given string. Finally these occurrences are printed using the foreach loop. The code snippet for this is given as follows:

MatchCollection match = regex.Matches("The numbers 3 and 5 are prime");
foreach (Match m in match)
{
     Console.WriteLine(m);
}

Program 2

A program that substitutes all the white spaces with underscore is given as follows:

using System;
using System.Text.RegularExpressions;
class Example
{
   static void Main()
   {
       string original_string = "C# is fun";
       string replace = "_";
        Regex regex = new Regex(@"\s+");
        string modified_string = regex.Replace(original_string, replace);
        Console.WriteLine("Original String: {0}", original_string);
        Console.WriteLine("Modified String: {0}", modified_string);    
   }
}

Source Code: Program that substitutes all the white spaces with underscore using regular expressions in C#

The output of the above program is as follows:

Original String: C# is fun
Modified String: C#_is_fun

Now let us understand the above program.

The original string is “C# is fun” and all the white spaces in the string need to be replaced with underscore. Then the Regex class constructor is used and it uses a pattern that specifies one or more whitespace characters. The code snippet for this is given as follows:

string original_string = "C# is fun";
       string replace = "_";
        Regex regex = new Regex(@"\s+");

Then the modified string is created where all the whitespace characters in the original string are replaced by underscore using the Replace() method. Finally, the original string and modified string are printed. The code snippet for this is given as follows:

string modified_string = regex.Replace(original_string, replace);
        Console.WriteLine("Original String: {0}", original_string);
        Console.WriteLine("Modified String: {0}", modified_string);
+91

By Signing up, you agree to ourTerms & Conditionsand ourPrivacy and Policy

Get your free handbook for CSM!!
Recommended Courses