C# VS2026
Lesson 22 of 30

Regular Expressions

C# in Visual Studio 2026 — a hands-on guide for developers at every level.

What are Regular Expressions?

A regular expression (regex) is a pattern that describes a set of strings. C# provides regex support through the System.Text.RegularExpressions namespace.

Basic Matching

using System.Text.RegularExpressions;

string text = "The price is $42.99 today.";

bool hasPrice = Regex.IsMatch(text, @"\$\d+\.\d{2}");
Console.WriteLine(hasPrice);  // True

Match m = Regex.Match(text, @"\$[\d\.]+");
Console.WriteLine(m.Value);    // $42.99

Common Regex Patterns

PatternMatches
\dDigit (0–9)
\wWord character (letter, digit, _)
\sWhitespace
.Any character except newline
^Start of string
$End of string
+One or more
*Zero or more
{n}Exactly n times

Find All Matches

string log = "Errors: 404 Not Found, 500 Internal, 403 Forbidden";
MatchCollection codes = Regex.Matches(log, @"\d{3}");
foreach (Match match in codes)
    Console.WriteLine(match.Value);  // 404, 500, 403

Replace and Groups

// Replace
string cleaned = Regex.Replace("Hello   World", @"\s+", " ");

// Named groups
var match = Regex.Match("2026-03-15", @"(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})");
Console.WriteLine(match.Groups["year"].Value);   // 2026
Console.WriteLine(match.Groups["month"].Value);  // 03