Regular Expressions in C#: A Complete Guide for Beginners
Regular expressions (regex) are a powerful tool for searching, replacing, and validating strings based on a given pattern. In C# (.NET), working with regular expressions is implemented through the System.Text.RegularExpressions namespace. This article will help you master the basics: from creating simple patterns to using all the features of the Regex class.
1. Basics of Working with Regex in C#
First, include the namespace:
using System.Text.RegularExpressions;The Regex class provides static and instance methods. The simplest way to check if a string contains a substring matching a pattern is the IsMatch method:
string text = "Hello, my email: test@example.com";string pattern = @"\\w+@\\w+\\.\\w+"; // simple email pattern
bool hasEmail = Regex.IsMatch(text, pattern);Console.WriteLine(hasEmail); // TruePattern breakdown:
\\w+— one or more letters, digits, or underscores@— the "at" symbol\\.— escaped dot (without escaping, a dot means "any character")
For repeated calls, it is better to create a Regex object to avoid recompiling the pattern:
Regex emailRegex = new Regex(@"\\w+@\\w+\\.\\w+");Console.WriteLine(emailRegex.IsMatch("admin@site.ru")); // True2. Finding All Matches: Match and MatchCollection
The Match method returns the first match, while Matches returns all matches as a MatchCollection. Each Match object contains information about the found substring, its position, and length.
Example: extracting all numbers from a string
string data = "In 2023 there were 15 events, in 2024 — already 23.";string numberPattern = @"\\d+"; // one or more digits
MatchCollection matches = Regex.Matches(data, numberPattern);
foreach (Match match in matches){ Console.WriteLine($"Found: {match.Value} at position {match.Index}");}// Output:// Found: 2023 at position 3// Found: 15 at position 22// Found: 2024 at position 37// Found: 23 at position 51Working with Groups. Groups allow you to extract parts of a match. For example, when searching for a date in the format "dd.mm.yyyy", you can separately get the day, month, and year:
string input = "Today is 25.12.2024";string datePattern = @"(\\d{2})\\.(\\d{2})\\.(\\d{4})";
Match match = Regex.Match(input, datePattern);if (match.Success){ Console.WriteLine($"Day: {match.Groups[1].Value}"); // 25 Console.WriteLine($"Month: {match.Groups[2].Value}"); // 12 Console.WriteLine($"Year: {match.Groups[3].Value}"); // 2024}Groups are numbered starting from 1 (group 0 is the entire match). Named groups are more readable:
string namedPattern = @"(?<day>\\d{2})\\.(?<month>\\d{2})\\.(?<year>\\d{4})";match = Regex.Match(input, namedPattern);Console.WriteLine(match.Groups["day"].Value); // 253. Advanced Features: Replacements and Options
Text replacement with Regex.Replace. It allows not only to remove or replace a substring but also to use groups in the replacement string:
string phone = "+7 (123) 456-78-90";// Remove everything except digitsstring clean = Regex.Replace(phone, @"[^\\d]", "");Console.WriteLine(clean); // 71234567890
// Change format: (123) 456-78-90 → 123-456-7890string formatted = Regex.Replace(phone, @"\\((\\d{3})\\)\\s*(\\d{3})-(\\d{2})-(\\d{2})", "$1-$2-$3$4");Console.WriteLine(formatted); // 123-456-7890Important options (RegexOptions):