Regular Expressions in C#: Fundamentals of Working with the Regex Class
Regular expressions (regex) are a powerful tool for searching, extracting, replacing, and validating strings based on a given pattern. In C# (.NET), all work with regular expressions is concentrated in the System.Text.RegularExpressions namespace and the central Regex class. In this article, we will break down the basic and advanced capabilities of regular expressions in C# using practical examples.
1. The Regex Class: Basic Methods and Creating Patterns
To work with regular expressions in C#, you need to include the namespace:
using System.Text.RegularExpressions;The Regex class provides several key methods:
- IsMatch — checks if the string contains a match to the pattern.
- Match — returns the first match.
- Matches — returns all matches.
- Replace — replaces found matches with the specified string.
- Split — splits the string by matches.
A simple example of validating an email address:
string email = "user@example.com";string pattern = @"^[\\w\\.-]+@[\\w\\.-]+\\.\\w+$";bool isValid = Regex.IsMatch(email, pattern);Console.WriteLine(isValid); // TrueNote the @ symbol before the string — this is a verbatim string, which simplifies writing backslashes (\\) in patterns.
2. Searching and Extracting Data: The Match and Matches Methods
The Match method returns a Match object, which contains information about the first match. If there are no matches, the Success property will be false.
An example of extracting a phone number from text:
string text = "Call the number +7 (123) 456-78-90 or +7 (987) 654-32-10";string pattern = @"\\+7\\s?\\(\\d{3}\\)\\s?\\d{3}-\\d{2}-\\d{2}";MatchCollection matches = Regex.Matches(text, pattern);
foreach (Match match in matches){ Console.WriteLine(match.Value);}// Output:// +7 (123) 456-78-90// +7 (987) 654-32-10The Matches method returns a collection of all matches. You can also use capturing groups to extract individual parts:
string text = "ID: 12345, Price: 999.99";string pattern = @"Price:\\s*(\\d+\\.?\\d*)";Match match = Regex.Match(text, pattern);
if (match.Success){ string price = match.Groups[1].Value; Console.WriteLine($"Price: {price}"); // Price: 999.99}Capturing groups are denoted by parentheses () in the pattern. Group zero is the entire match, and groups 1 through N are the captured substrings.
3. Replacing and Splitting Strings: Replace and Split
The Replace method allows you to flexibly replace matches. It supports backreferences ($1, $2, etc.) for inserting captured groups.
An example of formatting a date from "YYYY-MM-DD" to "DD.MM.YYYY":
string date = "2025-03-15";string pattern = @"(\\d{4})-(\\d{2})-(\\d{2})";string replacement = "$3.$2.$1";string result = Regex.Replace(date, pattern, replacement);Console.WriteLine(result); // 15.03.2025The Split method splits a string by matches to the pattern. This is convenient for parsing CSV or logs:
string data = "apple;banana;cherry;grape";string pattern = @";";string[] fruits = Regex.Split(data, pattern);foreach (var fruit in fruits){ Console.WriteLine(fruit);}// Output:// apple// banana// cherry// grapeYou can also use more complex delimiters, such as multiple spaces or punctuation marks:
string text = "one two,three;four";string[] parts = Regex.Split(