C# Tutorial

C# String

C# Array

C# Flow Control

C# Class and Object

C# Inheritance

C# Interface

C# Collection

C# Generic

C# File I/O

C# Delegate and Event

C# Exception

C# Process and Thread

C# ADO.NET Database Operations

C# Regular Expression

Regular expressions (regex) are a powerful way to search, match, and manipulate text. In C#, the System.Text.RegularExpressions namespace provides classes for working with regular expressions. This tutorial will cover the following topics related to regular expressions in C#:

  • Creating a regex pattern
  • Matching a pattern
  • Capturing groups
  • Replacing matches
  • Splitting strings

Let's begin!

  • Creating a regex pattern

To create a regex pattern, you can use the Regex class:

using System.Text.RegularExpressions;

string pattern = @"^\d{3}-\d{2}-\d{4}$";
Regex regex = new Regex(pattern);

In this example, we create a regex pattern to match US Social Security numbers (SSNs) in the format 123-45-6789. The @ symbol before the string indicates a verbatim string literal, which allows you to use backslashes in the regex pattern without having to escape them.

  • Matching a pattern

To check if a string matches a regex pattern, use the IsMatch method:

string input = "123-45-6789";
bool isMatch = regex.IsMatch(input);
Console.WriteLine(isMatch);  // Output: True

To find all matches of a regex pattern in a string, use the Matches method:

string input = "John's SSN is 123-45-6789, and Jane's SSN is 987-65-4321.";
MatchCollection matches = regex.Matches(input);

foreach (Match match in matches)
{
    Console.WriteLine(match.Value);
}

This will output:

123-45-6789
987-65-4321
  • Capturing groups

Capturing groups allow you to extract specific parts of a match. To define a capturing group, use parentheses () in your regex pattern:

string pattern = @"(\d{3})-(\d{2})-(\d{4})";
Regex regex = new Regex(pattern);

To access the captured groups of a match, use the Groups property:

string input = "123-45-6789";
Match match = regex.Match(input);

if (match.Success)
{
    Console.WriteLine($"Area Number: {match.Groups[1].Value}");
    Console.WriteLine($"Group Number: {match.Groups[2].Value}");
    Console.WriteLine($"Serial Number: {match.Groups[3].Value}");
}

This will output:

Area Number: 123
Group Number: 45
Serial Number: 6789
  • Replacing matches

To replace all matches of a regex pattern with a specified string, use the Replace method:

string input = "John's SSN is 123-45-6789, and Jane's SSN is 987-65-4321.";
string replacement = "XXX-XX-XXXX";
string result = regex.Replace(input, replacement);
Console.WriteLine(result);

This will output:

John's SSN is XXX-XX-XXXX, and Jane's SSN is XXX-XX-XXXX.
  • Splitting strings

To split a string by a regex pattern, use the Split method:

string input = "John, 25; Jane, 28; Mike, 30";
string pattern = @"\s*[,;]\s*";
Regex regex = new Regex(pattern);
string[] result = regex.Split(input);

foreach (string item in result)
{
    Console.WriteLine(item);
}
  1. How to use regular expressions in C#

    Regular expressions (regex) in C# are powerful tools for pattern matching and manipulation.

    using System;
    using System.Text.RegularExpressions;
    
    class Program
    {
        static void Main()
        {
            string input = "Hello, Regex in C#!";
            string pattern = @"[aeiou]";
            Regex regex = new Regex(pattern);
    
            MatchCollection matches = regex.Matches(input);
    
            foreach (Match match in matches)
            {
                Console.WriteLine(match.Value);
            }
        }
    }
    
  2. Regex class in C#

    The Regex class in C# provides methods and properties for working with regular expressions.

    Regex regex = new Regex(pattern);
    
  3. Regular expression patterns in C#

    Regular expression patterns define the rules for matching.

    string pattern = @"\d{3}-\d{2}-\d{4}";
    
  4. Match and search with regex in C#

    Use Match or IsMatch to find matches or check if a pattern exists.

    Match match = regex.Match(input);
    bool isMatch = regex.IsMatch(input);
    
  5. Regex options in C#

    Options like IgnoreCase or Multiline can be set to modify regex behavior.

    Regex regexWithOptions = new Regex(pattern, RegexOptions.IgnoreCase);
    
  6. Quantifiers and character classes in C# regex

    Quantifiers (*, +, ?) control the number of occurrences, and character classes ([a-z]) match sets of characters.

    string patternQuantifier = @"\d+";
    string patternCharClass = @"[aeiou]";
    
  7. Grouping and capturing in C# regular expressions

    Use parentheses for grouping and capturing specific parts of a match.

    string patternGroup = @"(\d{2})-(\d{2})";
    
  8. C# regex and replacement patterns

    Replace patterns within a string using Regex.Replace.

    string replaced = regex.Replace(input, "****");
    
  9. Named groups in C# regex

    Assign names to groups for better readability and access.

    string patternNamedGroup = @"(?<Year>\d{4})-(?<Month>\d{2})-(?<Day>\d{2})";
    
  10. Lookahead and lookbehind in C# regex

    Use lookahead ((?=...)) and lookbehind ((?<=...)) for conditional matching.

    string patternLookahead = @"\d{3}(?=-)";
    string patternLookbehind = @"(?<=@)\w+";
    
  11. Using regular expressions for input validation in C#

    Regular expressions are commonly used for validating input patterns.

    if (Regex.IsMatch(input, @"\b[A-Za-z]+\b"))
    {
        Console.WriteLine("Valid word input");
    }
    
  12. Regex.Escape and Regex.Unescape in C#

    Escape and unescape strings for literal matching.

    string escapedPattern = Regex.Escape("[.*]");