Generate C# code from a regex
Drop a pattern in, pick flags, and get a .NET Regex snippet — IsMatch, Match, Matches, Replace, Split — using @"..." verbatim strings so backslashes stay readable.
using System;
using System.Linq;
using System.Text.RegularExpressions;
class Program {
static void Main() {
string input = @"Reach alice@example.com or bob@test.org.";
var re = new Regex(@"\\b\\w+@\\w+\\.\\w+\\b", RegexOptions.None);
bool isMatch = re.IsMatch(input);
Match first = re.Match(input);
MatchCollection all = re.Matches(input);
string replaced = re.Replace(input, @"[email]");
string[] parts = re.Split(input);
Console.WriteLine($"isMatch={isMatch}");
Console.WriteLine($"first={(first.Success ? first.Value : null)}");
Console.WriteLine($"all=[{string.Join(", ", all.Select(m => m.Value))}]");
Console.WriteLine($"replaced={replaced}");
Console.WriteLine($"parts=[{string.Join(", ", parts)}]");
}
}How to use a regex in C#
.NET's Regex class lives in System.Text.RegularExpressions. Verbatim strings (@\"…\") keep backslashes literal.
- 01
Type a pattern
Verbatim strings (@"...") preserve backslashes, so you write \b once instead of \\b. Double quotes inside are escaped as "".
Patterns are parsed with the JavaScript RegExp constructor, so syntax errors surface immediately and engine quirks like Unicode property escapes (\p{L}) require the u flag.
patternECMAScriptliteralregexinput · literalpattern · regex@"\b\w+@\w+\b"
loaded · ECMAScripttarget · ready - 02
Tune flags
JS i/m/s map to RegexOptions.IgnoreCase, Multiline, Singleline. JS u has no .NET equivalent — .NET regex is Unicode-aware by default.
Each flag character mirrors the ECMAScript literal: g enables iteration, i folds case, m anchors per line, s lets . match newlines, u unlocks proper Unicode, y is sticky, and d emits indices.
flagssampleg · i · mliveconfig · optionsflags · flagsRegexOptions.IgnoreCase
flags applied · livelive · preview - 03
Read the snippet
Includes IsMatch (boolean), Match (first), Matches (all), Replace, and Split — all printing into Console.WriteLine.
The generator rewrites the regex for the target language — handling string-literal escaping, raw-string prefixes, and engine-specific syntax tweaks.
codegentargetsnippetcopyrun · outputpreview · codevar re = new Regex(@"…")
snippet · livecode · ready - 04
Copy code
One click copies the full Program class — paste into a .cs file or run with dotnet-script.
Copy writes via navigator.clipboard.writeText, so nothing transits the network and the output is byte-identical to what you see on screen.
copyexportclipboardblobexport · exportedready · savedCopied
ready to shipsuccess
Regex patterns that don't melt down
Use named groups
(?<year>\d{4}) reads better than $1 and survives reordering. Supported in ECMAScript 2018+.
Anchor strictly
Use ^/$ with the m flag when matching whole lines. Without anchors, partial matches sneak through.
Avoid catastrophic backtracking
Nested quantifiers like (a+)+ can explode. Run patterns through ReDoS Detector first.
Escape every literal
Backslash any meta character you want literally: \.\$\^\*\+\?\(\)\[\]\{\}\|\\.
Test edge cases
Empty string, single character, unicode, the maximum length you expect — write fixtures for each.
Patterns aren’t parsers
Don’t parse HTML, JSON, or balanced parens with regex. Use a proper parser when the grammar is recursive.
When to generate C# regex code
Skip the boilerplate when wiring a pattern into an ASP.NET app, an MVC validator, or an Azure Function.
Data annotation
Use [RegularExpression] on ViewModels for ASP.NET form validation. Compiles through the JavaScript RegExp constructor — engine quirks (Unicode property escapes, sticky matching, named groups) work when their flags are on. Error messages cite the exact position of any syntax issue.
ReDoS-safeConsole tools
Write quick C# scripts to scan logs or transform text files. Pairs with the ReDoS detector to catch catastrophic backtracking before you deploy. A pattern that handles 1k-character input fine can become a denial-of-service vector on attacker-controlled 1M-character input.
ECMA-compliantAzure Functions
Filter event payloads with IsMatch in an HTTP-triggered function. Output exports as JavaScript, Python re, Java util.regex, .NET System.Text.RegularExpressions, PCRE, and POSIX — language quirks are highlighted on conversion so you don't ship a JS-only pattern to a Go service.
spec-gradeSource generators
Use Regex inside a Roslyn source generator to extract symbols. Capture groups (named or numbered) round-trip cleanly into replacement strings, JSON output, or CSV extraction without re-typing. Backreferences ($1, ${name}) preserve semantics across languages.
cross-enginePowerShell interop
Reuse a .NET regex from PowerShell via [regex]::IsMatch. Test against edge cases — empty input, single character, max length, multibyte boundaries — to catch off-by-one and zero-length match bugs before they reach production.
test-readyWPF / WinForms
Validate user input as it changes in MVVM bindings. All matching runs client-side so secret patterns never leave the browser. Useful when the pattern itself is sensitive (PII regexes, internal data formats, security filters).
production-readyFrequently asked questions
Something missing?
Tell us what you need. We ship the top requests every two weeks.