C# Reference ยท Strings and Text
The Regex class
Reference for System.Text.RegularExpressions.Regex in C#: IsMatch, static versus instance methods, Split, Escape, match timeouts and catastrophic backtracking.
Regex in System.Text.RegularExpressions searches and rewrites text using patterns. You can call its static methods for a one-off check, or create an instance once and reuse it. An instance holds the parsed pattern, so it is the faster choice when the same pattern runs many times.
The most common method is IsMatch, which answers "does this text contain the pattern?". Match, Matches and Replace give you the details; they have their own pages. Patterns are plain strings, so raw string literals ("""...""") or verbatim strings (@"...") save you from doubling every backslash.
using System.Text.RegularExpressions; bool hasDigits = Regex.IsMatch("order 66", @"\d+");
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public Regex(string pattern) public Regex(string pattern, RegexOptions options) public Regex(string pattern, RegexOptions options, TimeSpan matchTimeout) public bool IsMatch(string input) public static bool IsMatch(string input, string pattern) public static bool IsMatch(string input, string pattern, RegexOptions options, TimeSpan matchTimeout) public string[] Split(string input) public static string Escape(string str) public static string Unescape(string str)
| Name | Description |
|---|---|
pattern |
The regular expression text. |
options |
RegexOptions flags such as IgnoreCase. |
matchTimeout |
Longest time one match operation may take. Regex.InfiniteMatchTimeout means no limit. |
input |
The text to search. |
str |
Text to turn into a pattern that matches it literally. |
Returns: IsMatch returns true when the pattern is found anywhere in input. Split returns the pieces between matches. Escape returns text with metacharacters backslash-escaped.
Errors / undefined behavior: ArgumentNullException for a null input or pattern. RegexParseException (a subclass of ArgumentException) when the pattern is invalid. RegexMatchTimeoutException when the timeout expires.
Usage notes
IsMatchis a search, not a full match. Without^and$the pattern may match any part of the input. This is the most common validation bug.- Static versus instance. The static methods look the pattern up in a small internal cache (15 entries by default), which is convenient but wasteful for many patterns. Keep a
static readonly Regexfield for hot paths, or use[GeneratedRegex]. - Always set a timeout for untrusted input. Patterns with nested quantifiers such as
(a+)+can take exponential time (ReDoS). Pass amatchTimeout, rewrite the pattern, or useRegexOptions.NonBacktracking, which guarantees linear time but does not support backreferences or lookarounds. - Escape user text.
Regex.Escapemakes.,+,(and friends literal. For plain substring tests,string.Containsis simpler and faster. - Thread safety.
Regexinstances are immutable and safe to share between threads. - Culture. Case-insensitive matching uses the current culture unless you add
RegexOptions.CultureInvariant. Our runner runs in the invariant culture, so the difference is invisible here. - Do not parse everything with regex. HTML, JSON and nested structures need a real parser.