Regular Expressions - Powerful Pattern Matching in C#

Vaibhav • September 10, 2025

Regular expressions (regex) are a powerful tool for searching, matching, and extracting complex patterns in text. Whether you need to validate an email, extract numbers, or find all words starting with a capital letter, regex lets you describe these patterns concisely. In C#, the System.Text.RegularExpressions namespace provides everything you need for regex-based string processing. This article covers the essentials: creating regex patterns, matching, extracting, replacing, and best practices for safe, readable, and efficient regex use.

1) What is a regular expression?

A regular expression is a mini-language for describing patterns in text. For example:

  • \d+ - one or more digits
  • \w+ - one or more word characters (letters, digits, underscore)
  • [A-Z][a-z]+ - a capital letter followed by lowercase letters
  • ^abc - "abc" at the start of a line
  • @gmail\.com$ - ends with "@gmail.com"

2) Basic usage - Regex.IsMatch, Regex.Match, Regex.Matches

The Regex class provides static and instance methods for matching and extracting.

using System.Text.RegularExpressions;

// Check if a string contains a number
string input = "Order #12345";
bool hasNumber = Regex.IsMatch(input, @"\d+"); // True

// Extract the first number
Match m = Regex.Match(input, @"\d+");
if (m.Success)
    Console.WriteLine(m.Value); // "12345"

// Find all numbers in a string
string text = "A1 B22 C333";
foreach (Match match in Regex.Matches(text, @"\d+"))
    Console.WriteLine(match.Value); // "1", "22", "333"
  • IsMatch - does the pattern exist?
  • Match - get the first match (with details)
  • Matches - get all matches (as a collection)

3) Common regex patterns and what they do

  • \d - digit (0-9)
  • \w - word character (letter, digit, underscore)
  • \s - whitespace
  • . - any character except newline
  • [abc] - "a", "b", or "c"
  • [^abc] - any character except "a", "b", or "c"
  • ^ - start of string/line
  • $ - end of string/line
  • * - zero or more
  • + - one or more
  • ? - zero or one (optional)
  • {n,m} - between n and m times

4) Extracting groups - capturing parts of a match

Use parentheses () to capture parts of a match for later use.

string email = "[email protected]";
Match match = Regex.Match(email, @"^(\w+)@(\w+\.\w+)$");
if (match.Success)
{
    string user = match.Groups[1].Value;  // "user"
    string domain = match.Groups[2].Value; // "example.com"
    Console.WriteLine($"User: {user}, Domain: {domain}");
}
  • Groups[0] is the whole match; Groups[1], Groups[2], etc. are captures.
  • Use named groups: (?<name>pattern) for clarity.

5) Replacing text with Regex.Replace

Use Regex.Replace to substitute all matches of a pattern with a replacement string.

string messy = "Phone: 123-456-7890";
string clean = Regex.Replace(messy, @"\D", ""); // Remove all non-digits: "1234567890"
  • Replacement can use captured groups: $1, ${name}
  • Great for cleaning, reformatting, or anonymizing data.

6) Case-insensitive and multiline options

Pass RegexOptions.IgnoreCase or RegexOptions.Multiline for more control.

string text = "Hello\nWorld";
bool found = Regex.IsMatch(text, "^world", RegexOptions.IgnoreCase | RegexOptions.Multiline); // True
  • IgnoreCase - match regardless of case.
  • Multiline - ^ and $ match start/end of each line, not just the whole string.

7) Defensive regex - nulls, empty strings, and timeouts

  • Always check Match.Success before using groups.
  • Handle null and empty input gracefully.
  • For untrusted patterns or very large input, use Regex.MatchTimeout to avoid runaway matches.
string s = null;
if (!string.IsNullOrEmpty(s) && Regex.IsMatch(s, @"\d+"))
    Console.WriteLine("Has a number!");

8) Practical mini-project: extracting all email addresses from text

string text = "Contact: [email protected], [email protected]";
var emails = Regex.Matches(text, @"\b[\w\.-]+@[\w\.-]+\.\w+\b");
foreach (Match m in emails)
    Console.WriteLine(m.Value);
// Output: [email protected], [email protected]
  • Pattern matches most simple email addresses (not all edge cases).
  • Great for log scanning, data extraction, or validation.

9) Checklist - regex habits for robust code

  • Use IsMatch for yes/no checks, Match for details, Matches for all results.
  • Use Replace for cleaning or reformatting.
  • Capture groups for extracting parts of matches.
  • Specify RegexOptions for case/multiline as needed.
  • Validate input and check Success before using results.
  • Document your patterns for maintainability.

Summary

Regular expressions unlock powerful pattern matching and extraction in C#. Use Regex for searching, extracting, and replacing complex text patterns. Start with simple patterns, use groups for capturing, and always validate input and results. With these patterns, your code will be ready for real-world data cleaning, validation, and parsing tasks.