Regular Expressions in C# with Examples: In Practice

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Regular Expressions in C# with Examples: From Theory to Practice

\n\n

Regular expressions (regex) are a powerful tool for searching, extracting, and replacing text based on patterns. In C# (.NET), working with regex is implemented through the System.Text.RegularExpressions namespace and the Regex class. In this article, we will cover the main features with real examples: from simple search to email and phone validation.

\n\n

1. Basics: The Regex Class and Its Methods

\n\n

The main class for working with regex is Regex. It provides static and instance methods. Here are the main ones:

\n\n
    \n
  • IsMatch — checks if the string contains a match for the pattern.
  • \n
  • Match — finds the first match.
  • \n
  • Matches — finds all matches.
  • \n
  • Replace — replaces matches with a specified string.
  • \n
  • Split — splits the string based on a pattern.
  • \n
\n\n

Example 1. Simple Check

\n
using System;\nusing System.Text.RegularExpressions;\n\nclass Program\n{\n    static void Main()\n    {\n        string text = "Hello, my number: 123-456-7890";\n        string pattern = @"\\d{3}-\\d{3}-\\d{4}";\n\n        if (Regex.IsMatch(text, pattern))\n        {\n            Console.WriteLine("Number found!");\n        }\n    }\n}\n
\n\n

In this example, \\d{3} means "exactly three digits". The backslash is escaped using @ (verbatim string).

\n\n

2. Capture Groups and Data Extraction

\n\n

Capture groups allow you to extract parts of a match. They are defined with parentheses (). Each group gets a sequential number (starting from 1).

\n\n

Example 2. Extracting Username and Domain from an Email

\n
string email = "user@example.com";\nstring pattern = @"^(\\w+)@(\\w+\\.\\w+)$";\n\nMatch match = Regex.Match(email, pattern);\n\nif (match.Success)\n{\n    Console.WriteLine($"Username: {match.Groups[1].Value}");   // user\n    Console.WriteLine($"Domain: {match.Groups[2].Value}");   // example.com\n}\n
\n\n

Here, (\\w+) captures one or more alphanumeric characters. ^ and $ are anchors for the start and end of the string.

\n\n

Example 3. Parsing a URL

\n
string url = "https://pythonlib.ru/page?id=42";\nstring pattern = @"^(https?)://([^/]+)(/.*)?$";\n\nMatch m = Regex.Match(url, pattern);\nif (m.Success)\n{\n    Console.WriteLine($"Protocol: {m.Groups[1].Value}"); // https\n    Console.WriteLine($"Domain: {m.Groups[2].Value}");    // pythonlib.ru\n    Console.WriteLine($"Path: {m.Groups[3].Value}");     // /page?id=42\n}\n
\n\n

3. Text Replacement and Removal

\n\n

The Replace method allows you to replace found fragments. You can use backreferences like $1, $2 to insert groups.

\n\n

Example 4. Formatting a Phone Number

\n
string raw = "89161234567";\nstring pattern = @"(\\d{1})(\\d{3})(\\d{3})(\\d{2})(\\d{2})";\nstring replacement = "+7 ($2) $3-$4-$5";\n\nstring formatted = Regex.Replace(raw, pattern, replacement);\nConsole.WriteLine(formatted); // +7 (916) 123-45-67\n
\n\n

Example 5. Removing Extra Spaces

\n
string text = "This    text   has    extra   spaces.";\nstring cleaned = Regex.Replace(text, @"\\s+", " ");\nConsole.WriteLine(cleaned); // "This text has extra spaces."\n
\n\n

\\s+ — one or more whitespace characters. We replace them with a single space.

\n\n

4. Real-World Cases: Email and Phone Validation

\n\n

In practice, regex is most often used for validating user input. Here are two typical examples.

\n\n

Email Validation (Simplified)

\n
public static bool IsValidEmail(string email)\n{\n    if (string.IsNullOrWhiteSpace(email))\n        return false;\                

Blogs

Book Recommendations