top

Search

C# Tutorial

Regular expressions denote different patterns like literals, constructs, operators etc. that can be matched with the input.Regex ClassThe immutable regular expressions are represented using a Regex Class. Details about the Regex class is given as follows:Constructors in Regex ClassThe different constructors and their description is given as follows:Table: Constructors in Regex Class in C#Source: MSDNConstructorsDescriptionRegex()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 expressionRegex(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.Fields in Regex ClasszThe different fields and their description is given as follows:Table: Fields in Regex Class in C#FieldsDescriptioncapnamesThis field is used by a Regex object generated by the CompileToAssembly method.capsThis field is used by a Regex object generated by the CompileToAssembly method.capsizeThis field is used by a Regex object generated by the CompileToAssembly method.capslistThis field is used by a Regex object generated by the CompileToAssembly method.factoryThis field is used by a Regex object generated by the CompileToAssembly method.InfiniteMatchTimeoutThis timeout is used by a Regex object generated by the CompileToAssembly method.internalMatchTimeoutThis timeout is the maximum amount of time that can elapse in a pattern-matching operation before the operation times out.patternThis field is used by a Regex object generated by the CompileToAssembly method.roptionsThis field is used by a Regex object generated by the CompileToAssembly method.Properties in Regex ClassThe different properties and their description is given as follows:Table: Properties in Regex Class in C#Source: MSDNPropertiesDescriptionCacheSizeThis property gets or sets the maximum number of entries in the current static cache of compiled regular expressions.CapNamesThis property gets or sets a dictionary that maps named capturing groups to their index values.CapsThis property gets or sets a dictionary that maps numbered capturing groups to their index values.MatchTimeoutThis property gets the time-out interval of the current instance.OptionsThis property gets the options that were passed into the Regex constructor.RightToLeftThis property gets a value that indicates whether the regular expression searches from right to left.Methods in Regex ClassThe different methods and their description is given as follows:Table: Methods in Regex Class in C#Source: MSDNMethodsDescriptionCompileToAssembly(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.Program 1A program that displays all the patterns of one or more digits is given as follows:Source Code: Program that displays all the patterns of one or more digits using regular expressions in C#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);         }    } }The output of the above program is as follows:3 5Now 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 occurences 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 2A program that substitutes all the white spaces with underscore is given as follows:Source Code: Program that substitutes all the white spaces with underscore using regular expressions in C#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);        } }The output of the above program is as follows:Original String: C# is fun Modified String: C#_is_funNow 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);
logo

C# Tutorial

Regular Expressions in C#

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:

Table: Constructors in Regex Class in C#

Source: MSDN

ConstructorsDescription
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.

Fields in Regex Classz

The different fields and their description is given as follows:

Table: Fields in Regex Class in C#

FieldsDescription
capnamesThis field is used by a Regex object generated by the CompileToAssembly method.
capsThis field is used by a Regex object generated by the CompileToAssembly method.
capsizeThis field is used by a Regex object generated by the CompileToAssembly method.
capslistThis field is used by a Regex object generated by the CompileToAssembly method.
factoryThis field is used by a Regex object generated by the CompileToAssembly method.
InfiniteMatchTimeoutThis timeout is used by a Regex object generated by the CompileToAssembly method.
internalMatchTimeoutThis timeout is the maximum amount of time that can elapse in a pattern-matching operation before the operation times out.
patternThis field is used by a Regex object generated by the CompileToAssembly method.
roptionsThis field is used by a Regex object generated by the CompileToAssembly method.

Properties in Regex Class

The different properties and their description is given as follows:

Table: Properties in Regex Class in C#

Source: MSDN

PropertiesDescription
CacheSizeThis property gets or sets the maximum number of entries in the current static cache of compiled regular expressions.
CapNamesThis property gets or sets a dictionary that maps named capturing groups to their index values.
CapsThis property gets or sets a dictionary that maps numbered capturing groups to their index values.
MatchTimeoutThis property gets the time-out interval of the current instance.
OptionsThis property gets the options that were passed into the Regex constructor.
RightToLeftThis property gets a value that indicates whether the regular expression searches from right to left.

Methods in Regex Class

The different methods and their description is given as follows:

Table: Methods in Regex Class in C#

Source: MSDN

MethodsDescription
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.

Program 1

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

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

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);
        }
   }
}

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 occurences 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:

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

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);    
   }
}

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);

Leave a Reply

Your email address will not be published. Required fields are marked *

Comments

austin faith

Avery good write-up. Please let me know what are the types of C# libraries used for AI development.

kariya arti

very satisfied!!

jean-Francois Michaud

Good tutorial. Small question: Say, there is : enum numbers { one, two, three} and a string field_enum ="one" how would I from the variable field_enum have a response with value numbers.one so that it can be treated as an enum and not as a string. making a list from the enum, and loop into the list. is not elegant... and may not work is forced value on field is forced ( one = 100).

Kshitiz

Hi Team Knowledge Hut, Thank you for such an informative post like this. I am completely new to this digital marketing field and do not have much idea about this, but your post has become a supportive pillar for me. After reading the blog I would expect to read more about the topic. I wish to get connected with you always to have updates on these sorts of ideas. Regards, Kshitiz

Ed

The reason abstraction can be used with this example is because, the triangle, circle. Square etc can be defined as a shape, for example.....shape c = new circle(5,0)...the abstract object c now points at the circle class. Thus hiding implementation

Suggested Tutorials

Swift Tutorial

Introduction to Swift Tutorial
Swift Tutorial

Introduction to Swift Tutorial

Read More

R Programming Tutorial

R Programming

Python Tutorial

Python Tutorial