Regular Expressions in C# with Examples: In Practice
Regular expressions (regex) are a powerful tool for searching, validating, and replacing text based on patterns. In C# (.NET), they are implemented through the System.Text.RegularExpressions.Regex class. In this article, we will explore the main capabilities using real-world examples: from simple email validation to extracting data from HTML. All examples are ready to copy and use in your projects.
Basics of Working with Regex in C#
The Regex class provides three key methods:
- IsMatch — checks if a string matches a pattern;
- Match — finds the first match;
- Matches — finds all matches.
A simple example — checking if a string contains digits:
using System;using System.Text.RegularExpressions;
public class RegexExample{ public static void Main() { string text = "My number: 12345"; string pattern = @"\\d+"; // one or more digits
bool hasDigits = Regex.IsMatch(text, pattern); Console.WriteLine(hasDigits); // True }}Note the @ before the string — this is a verbatim string literal, which disables backslash escaping. Without it, you would have to write "\\\\d+".
Email and Phone Number Validation
Email Validation
Email validation is a classic task. A simple but working pattern:
public static bool IsValidEmail(string email){ string pattern = @"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"; return Regex.IsMatch(email, pattern);}
// UsageConsole.WriteLine(IsValidEmail("user@example.com")); // TrueConsole.WriteLine(IsValidEmail("user@.com")); // FalseLet's break down the pattern:
^— start of string;[a-zA-Z0-9._%+-]+— local part (letters, digits, and special characters);@— the "at" symbol;[a-zA-Z0-9.-]+— domain;\\.— dot (escaped);[a-zA-Z]{2,}— top-level domain (at least 2 letters);$— end of string.
Phone Number Validation
Example for Russian format (+7 XXX XXX-XX-XX):
public static bool IsValidRussianPhone(string phone){ string pattern = @"^\\+7\\d{3}\\d{3}-\\d{2}-\\d{2}$"; // Or a more flexible variant: // @"^\\+7[\\s-]?\\d{3}[\\s-]?\\d{3}[\\s-]?\\d{2}[\\s-]?\\d{2}$" return Regex.IsMatch(phone, pattern);}Extracting Data from Text Using Capture Groups
Capture groups (parentheses ()) allow you to extract parts of a match. For example, let's extract all emails from text:
string text = "Contacts: support@site.com, admin@test.org, info@company.net";string pattern = @"([a-zA-Z0-9._%+-]+)@([a-zA-Z0-9.-]+)\\.([a-zA-Z]{2,})";
MatchCollection matches = Regex.Matches(text, pattern);foreach (Match match in matches){ Console.WriteLine($"Full email: {match.Value}"); Console.WriteLine($"Local part: {match.Groups[1].Value}"); Console.WriteLine($"Domain: {match.Groups[2].Value}"); Console.WriteLine($"TLD: {match.Groups[3].Value}"); Console.WriteLine("---");}Result:
Full email: support@site.comLocal part: supportDomain: siteTLD: com---Groups are numbered starting from 1 (group 0 is the entire match). You can also name them:
string pattern = @"(?<user>[a-zA-Z0-9._%+-]+)@(?<domain>[a-zA-Z0-9.-]+)\\.(?<tld>[a-zA-Z]{2,})";// Access: match.Groups["user"].ValueExtracting Links from HTML
string html = @"<a href='https://example.com'>Examp