Mastering the Regex Class in C#: Methods and Practical Usage

Explore the powerful Regex class in C# and learn how to use methods like IsMatch, Match, Matches, Replace, and Split. Enhance your string manipulation and pattern matching skills with practical examples and clear explanations.



Understanding the Regex Class

The Regex class in C# offers several methods for working with regular expressions:

  • IsMatch(string input): Returns true if the pattern matches the entire input string, false otherwise.
  • Match(string input): Returns a Match object representing the first occurrence of the pattern in the input string.
  • Matches(string input): Returns a MatchCollection containing 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 specified replacement.
  • Split(string input): Splits the input string into an array of substrings based on the pattern.

Using Regex in C#

To use regex in your C# code, follow these steps:

Import the namespace:

Syntax

using System.Text.RegularExpressions;

Create a Regex object:

Syntax

string pattern = @"hello";
Regex regex = new Regex(pattern);

Apply regex methods:

Syntax

string input = "hello world!";
bool isMatch = regex.IsMatch(input);
Match match = regex.Match(input);
MatchCollection matches = regex.Matches(input);
string replacedString = regex.Replace(input, "goodbye");
string[] splitStrings = regex.Split(input);
Output

true, "hello", "goodbye world!", ["hello", "world!"]

Example: Finding Email Addresses

Syntax

using System.Text.RegularExpressions;

public class RegexExample
{
public static void Main()
{
string pattern = @"\w+@\w+\.\w+";
string input = "Contact us at support@example.com or sales@example.com";
Regex regex = new Regex(pattern);
MatchCollection matches = regex.Matches(input);

foreach (Match match in matches)
{
    Console.WriteLine(match.Value);
}
}
}
Output

support@example.com
sales@example.com

Handling Regex Exceptions

To prevent unexpected errors, use a try-catch block to handle potential exceptions:

Syntax

try
{
// Regex operations
}
catch (RegexMatchTimeoutException ex)
{
Console.WriteLine("Regex timeout: {0}", ex.Message);
}
catch (RegexParseException ex)
{
Console.WriteLine("Regex parse error: {0}", ex.Message);
}
Output

Regex timeout: The operation has timed out.
Regex parse error: Unexpected end of pattern.

Additional Tips

  • Use verbatim string literals (@) to avoid escaping backslashes in patterns.
  • Explore regex options to modify matching behavior (e.g., IgnoreCase, Multiline).
  • Leverage named capture groups to extract specific parts of matches.
  • Consider performance implications for complex patterns or large input strings.

Conclusion

By mastering these concepts and best practices, you can effectively harness the power of regular expressions in your C# applications.