Regex in C#

In C#, the System.Text.RegularExpressions namespace includes the Regex Class that provides several methods for working with regular expressions.

Regex Method Description
IsMatch(string input) Returns true if the pattern matches the input string.
Match(string input) Returns the first occurrence of the pattern in the input string.
Matches(string input) Returns all occurrences of the pattern in the input string.
Replace(string input, string replacement) Replaces all occurrences of the pattern in the input string with the replacement string.
Split(String) Splits an input string into an array of substrings at the positions defined by a regular expression pattern.

Check all the Regex methods for more information.

Using Regex in C#

To use regex in your C# code, you first need to create a Regex object, which represents the regex pattern that you want to match. Here's an example of how to create a Regex object that matches the word "hello" in a text:

Example: Use Regex in C#
string regexPattern = @"hello";
Regex regex = new Regex(regexPattern);
string inputString = "hello world!";
Match match = regex.Match(inputString);

if (match.Success)
{
    Console.WriteLine("Match found at index {0} with length {1}", match.Index, match.Length);
}
else
{
    Console.WriteLine("No match found.");
}

In this example, regexPattern is the simple regex pattern is used to search for "hello" in the input string. The regex object is created by passing a regex pattern string. The regex.Match() method searches for the first match of the regexPattern in the inputString. If a match is found, the match.Success property will be true, and you can use the match.Index and match.Length properties to get the index and length of the match in the string.

You can also use the Matches() method to find all matches of a regex pattern in a string. The Matches method returns a MatchCollection object, which contains all the matches in the string. The following example demonstrates finding all matches of the word "hello" in a text:

Example: Use Regex in C#
string regexPattern = @"hello";
Regex regex = new Regex(regexPattern);
string inputString = "hello world! hello again!";
MatchCollection matches = regex.Matches(inputString);

foreach (Match match in matches)
{
    Console.WriteLine("Match found at index {0} with length {1}", match.Index, match.Length);
}

In this example, the Matches() method searches for all matches of the regex pattern in the text string. The foreach loop iterates over each match in the MatchCollection, and you can use the match.Index and match.Length properties to get the index and length of each match in the string.

Regex in C# is a powerful tool for text processing and data validation. By understanding the basics of regex patterns and the Regex class in C#, you can use regex to extract data from strings, validate user input, and more.

Handling Regex Exceptions

You can catch regex specific exceptions when working with regular expressions in C#.

The followings exceptions can be thrown while working with regular expressions in C#:

  • RegexMatchTimeoutException: This exception is thrown when the regular expression engine times out while attempting to match a pattern to an input string. The timeout can be set using the RegexOptions parameter in the Regex constructor.
  • RegexParseException: This exception is thrown when the regular expression pattern cannot be parsed.

The following demonstrates exception handling using a try-catch block around the code that calls the Regex class.

Example: Regex Exception Handling
public static void Main(string[] args)
{
	try
	{
		string regexPattern = @"\hel#lo\m";
		Regex regex = new Regex(regexPattern);
		string inputString = "hello world!";
		Match match = regex.Match(inputString);

		if (match.Success)
		{
			Console.WriteLine("Match found.");
		}
		else
		{
			Console.WriteLine("No match found.");
		}
	}
	catch (RegexMatchTimeoutException ex)
	{
		Console.WriteLine("Timeout Error: " + ex.Message);
	}
	catch (RegexParseException ex)
	{
		Console.WriteLine("Error in parsing regular expression: " + ex.Message);
	}
}