Regular Expressions in C#

Our first program demonstrates the use of regular expressions in C#. Here’s the full source code:

using System;
using System.Text.RegularExpressions;

class RegularExpressions
{
    static void Main()
    {
        // This tests whether a pattern matches a string.
        bool match = Regex.IsMatch("peach", @"p([a-z]+)ch");
        Console.WriteLine(match);

        // For other regex tasks, you'll need to create a Regex object.
        Regex r = new Regex(@"p([a-z]+)ch");

        // Many methods are available on these objects. Here's
        // a match test like we saw earlier.
        Console.WriteLine(r.IsMatch("peach"));

        // This finds the match for the regex.
        Console.WriteLine(r.Match("peach punch").Value);

        // This finds the first match but returns the
        // start and end indexes for the match instead of the
        // matching text.
        Match m = r.Match("peach punch");
        Console.WriteLine($"idx: [{m.Index}, {m.Index + m.Length}]");

        // The Group property provides information about
        // both the whole-pattern matches and the submatches
        // within those matches.
        m = r.Match("peach punch");
        Console.WriteLine($"[{m.Value}, {m.Groups[1].Value}]");

        // The Captures property provides information about
        // the indexes of matches and submatches.
        m = r.Match("peach punch");
        Console.WriteLine($"[{m.Index}, {m.Index + m.Length}, {m.Groups[1].Index}, {m.Groups[1].Index + m.Groups[1].Length}]");

        // The Matches method finds all matches in the input.
        MatchCollection matches = r.Matches("peach punch pinch");
        foreach (Match match in matches)
        {
            Console.Write(match.Value + " ");
        }
        Console.WriteLine();

        // We can also get all the match information.
        matches = r.Matches("peach punch pinch");
        Console.Write("all: ");
        foreach (Match match in matches)
        {
            Console.Write($"[{match.Index}, {match.Index + match.Length}, {match.Groups[1].Index}, {match.Groups[1].Index + match.Groups[1].Length}] ");
        }
        Console.WriteLine();

        // The Replace method can be used to replace subsets of strings.
        Console.WriteLine(r.Replace("a peach", "<fruit>"));

        // The Regex.Replace method with a MatchEvaluator allows you to
        // transform matched text with a given function.
        string result = Regex.Replace("a peach", @"p([a-z]+)ch", m => m.Value.ToUpper());
        Console.WriteLine(result);
    }
}

To run the program, save it as RegularExpressions.cs and use the C# compiler:

$ csc RegularExpressions.cs
$ RegularExpressions.exe
True
True
peach
idx: [0, 5]
[peach, ea]
[0, 5, 1, 3]
peach punch pinch
all: [0, 5, 1, 3] [6, 11, 7, 9] [12, 17, 13, 15]
a <fruit>
a PEACH

This example demonstrates various operations with regular expressions in C#, including matching, finding, replacing, and transforming text based on patterns. The System.Text.RegularExpressions namespace provides the Regex class, which is the main class for working with regular expressions in C#.

For a complete reference on C# regular expressions, check the Regular Expression Language - Quick Reference in the Microsoft documentation.