Limited Offer
60% OFF on all plans!

Regex in C#

Write regular expressions using System.Text.RegularExpressions — Regex.IsMatch, Match, Matches, Replace, Groups, named captures, compiled regex, and source generators (C# 10+).

Introduction to Regular Expressions

1. What is a Regular Expression?

A regex is a pattern used to search, match, or replace text.

Creating Regular Expressions

1. new Regex() — Instance (Recommended for Reuse)

Create a `Regex` object when you plan to use the same pattern multiple times.

2. Regex.IsMatch() — Static Shorthand

Use static methods for one-off checks without creating an instance.

Regex Flags

1. Common RegexOptions Flags

Pass `RegexOptions` to change case sensitivity, multiline mode, etc.

Regex Methods

1. IsMatch() — Test if Pattern Exists

`IsMatch()` returns `true` if the pattern is found anywhere in the string.

2. Match() & Matches() — Find Matches

`Match()` returns the first match; `Matches()` returns all matches.

3. Replace() — Replace Matches

`Regex.Replace()` replaces all matches with a new string or via a lambda.

4. Split() — Split by Pattern

`Regex.Split()` splits a string on every match of the pattern.

Character Classes

1. Common Character Classes

Shorthand classes like `\d`, `\w`, `\s` and custom `[abc]` ranges.

Quantifiers

1. Common Quantifiers

`*`, `+`, `?`, `{n}`, `{n,m}` control repetition.

Anchors

1. ^ and $ Anchors

`^` matches the start; `$` matches the end of the string.

Groups & Alternation

1. Capturing Groups

Wrap part of a pattern in `()` to capture that portion.

2. Alternation (OR)

Use `|` to match one pattern or another.

Regex for Validation

1. Email Validation

A practical regex to validate basic email format.

2. Numeric String Validation

Validate integers, decimals, and phone numbers.