C# Check If String Matches Regex: IsMatch, Anchors, Timeouts and Unicode Pitfalls
How to check whether a string matches a regular expression in C#: Regex.IsMatch, full-string anchors, reusable and generated patterns, timeouts, Unicode caveats and when plain parsing is the better choice.
To check whether a string matches a regular expression in C#, call Regex.IsMatch from the System.Text.RegularExpressions namespace. It returns true or false and leaves the input untouched. The detail that trips up most validation code is that IsMatch succeeds when the pattern is found anywhere in the input, not only when the whole string fits. This review covers how to write a reliable regex check, what it does and does not tell you, where Unicode and copied patterns cause surprises, and when a plain string method or parser is the better tool.
The short answer
using System.Text.RegularExpressions;
bool isValid = Regex.IsMatch(input, @"^[0-9]{5}\z");
The verbatim string prefix (@) keeps backslashes literal, so the pattern reads as written. The ^ and \z anchors force the entire input to match; without them, any five consecutive digits inside a longer string would pass. Passing null as the input throws ArgumentNullException, so check for null first if the value can be missing.
Is a regex check the right tool for your input?
Recommendation: use a regex check when the rule is about the shape of text, such as a fixed-length code, an identifier with allowed characters, or a simple token format. The main benefit is that a single declarative pattern expresses the rule and can be tested in isolation. The decisive tradeoff is that a pattern checks form, not meaning: a date pattern can accept 2026-02-31, and a long email pattern can still reject valid addresses or accept invalid ones. Patterns are also easy to get subtly wrong and harder for the next developer to read than ordinary code.
Plain code or a dedicated parser is preferable in these cases:
- Exact or prefix comparisons: string.Equals, StartsWith, EndsWith or Contains with an explicit StringComparison are clearer and cannot misfire on special characters.
- Numbers and dates: int.TryParse, decimal.TryParse, DateTime.TryParseExact and DateOnly.TryParseExact validate both format and value range.
- URLs: Uri.TryCreate understands schemes, hosts and escaping that a hand-written pattern usually misses.
- Email addresses: a light shape check, or System.Net.Mail.MailAddress, followed by a confirmation message is more dependable than a strict pattern.
- Nested or structured formats such as JSON, XML or HTML: use a real parser; regular expressions cannot reliably validate nested structure.
What a regex check actually changes
Nothing. IsMatch only reads the input; .NET strings are immutable, so no method on Regex alters the original value. Regex.Replace is the method that transforms text, and it returns a new string rather than editing the old one. Keeping validation (IsMatch) separate from transformation (Replace) also makes it obvious when code is silently cleaning input instead of rejecting it.
The word "match" is ambiguous in everyday use. In .NET, IsMatch means "the pattern was found somewhere", which is a search, not a full-string comparison. Full-string validation needs anchors, and the choice of end anchor matters:
Regex.IsMatch("abc12345xyz", @"[0-9]{5}"); // true: digits found inside
Regex.IsMatch("abc12345xyz", @"^[0-9]{5}$"); // false: whole string must fit
Regex.IsMatch("12345\n", @"^[0-9]{5}$"); // true: $ also matches before a final newline
Regex.IsMatch("12345\n", @"^[0-9]{5}\z"); // false: \z means the absolute end
Use \A and \z (or ^ and \z) when a trailing newline should make the input invalid. If RegexOptions.Multiline is set, ^ and $ match at every line boundary, which turns a whole-string check into a per-line check; \A and \z are unaffected by that option.
IsMatch, Match or Matches
| Method | Returns | Use it when |
| Regex.IsMatch | bool | You only need a yes or no answer |
| Regex.Match | Match (check Success, read Groups) | You need the matched text or captured parts |
| Regex.Matches | MatchCollection | You need every occurrence in the input |
| Regex.Count (.NET 7 and later) | int | You only need how many occurrences exist |
For pure validation, IsMatch is the right choice: it can stop at the first success and does not build capture data you will throw away.
Writing the check for reuse
The static Regex.IsMatch methods are fine for occasional checks; .NET keeps a small cache of recently used static patterns. For a pattern used repeatedly, create one Regex instance and reuse it, or, on .NET 7 and later, let the source generator build the matcher at compile time:
using System.Text.RegularExpressions;
public static partial class Validators
{
[GeneratedRegex(@"^[0-9]{5}\z", RegexOptions.CultureInvariant)]
private static partial Regex ZipCode();
public static bool IsZipCode(string input) => ZipCode().IsMatch(input);
}
The generated version surfaces pattern errors at build time instead of at runtime and produces readable code you can step through. When using RegexOptions.IgnoreCase, add RegexOptions.CultureInvariant so case-insensitive comparison does not depend on the current culture of the machine running the code.
Set a timeout for untrusted input
By default a .NET regex has no match timeout. Patterns with nested or overlapping quantifiers can backtrack for a very long time on crafted input, which is a denial-of-service risk when the input comes from users. Pass a timeout and decide what a timeout means for your validation, usually "invalid":
var username = new Regex(
@"^[A-Za-z0-9_-]{3,20}\z",
RegexOptions.CultureInvariant,
TimeSpan.FromMilliseconds(100));
bool isValid;
try
{
isValid = username.IsMatch(input);
}
catch (RegexMatchTimeoutException)
{
isValid = false;
}
The timeout value in the example is illustrative, not a measured recommendation; choose one that fits your workload. On .NET 7 and later, RegexOptions.NonBacktracking guarantees processing time proportional to input length, at the cost of some features: lookarounds, backreferences and atomic groups are not supported in that mode.
Unicode details that change results
A .NET regex works on UTF-16 code units, the same units counted by string.Length. That is not the same as the characters a person sees, and it affects both character classes and length limits:
- \d matches any Unicode decimal digit, including digits from other scripts. Use [0-9] when only ASCII digits are acceptable, or RegexOptions.ECMAScript, which restricts \d, \w and \s to ASCII behavior.
- An emoji outside the Basic Multilingual Plane is stored as a surrogate pair, two UTF-16 units. A dot matches one unit, so ^.$ fails on a single such emoji, and a length rule like ^.{1,20}$ counts units, not visible symbols.
- Accented letters can be stored precomposed (one code point) or as a base letter plus a combining mark (two code points). A letter class such as \p{L} does not match the combining mark, which belongs to \p{M}.
- Emoji built from several code points, such as those with skin-tone modifiers or joiners, look like one symbol but span several units, so per-character limits behave unpredictably.
using System.Text;
using System.Text.RegularExpressions;
Regex.IsMatch("\u00E9", @"^\p{L}\z"); // true: precomposed é is one letter
Regex.IsMatch("e\u0301", @"^\p{L}\z"); // false: letter followed by a combining mark
Regex.IsMatch("e\u0301".Normalize(NormalizationForm.FormC), @"^\p{L}\z"); // true after normalization
Regex.IsMatch("\uD83D\uDE00", @"^.\z"); // false: one emoji is two UTF-16 units
These outcomes follow from the documented Unicode categories and UTF-16 storage; they are explanatory examples, not results from a recorded test run. Normalizing input to Form C before matching removes most of the precomposed-versus-decomposed difference. If a length rule must count what users see, count text elements with System.Globalization.StringInfo in code rather than in the pattern.
Will the pattern and results survive copying and sharing?
Patterns copied from other languages or online testers do not always behave the same in .NET. JavaScript-style /pattern/flags delimiters are not part of a .NET pattern; flags become RegexOptions values instead. Some constructs differ between flavors; for example, .NET has no possessive quantifiers and uses atomic groups written as (?>...) for the same purpose. Before trusting a copied pattern, run it against .NET in a unit test with both valid and invalid samples, including edge cases such as an empty string and a trailing newline.
Copying also affects the C# source itself. In a regular string literal every backslash must be doubled, which is a common source of broken patterns; verbatim strings (@"...") and, from C# 11, raw string literals ("""...""") avoid that. Text pasted into an input field can carry characters that look like nothing, such as non-breaking or zero-width spaces, and cause failures that seem inexplicable. When debugging, log the code points of the rejected input rather than the rendered text.
For people filling in a form, the pattern itself is not a usable explanation. Show a plain-language description of the expected format, such as "5 digits, no spaces", next to the field and in the error message, so the requirement is clear to anyone, including people relying on a screen reader. How specific assistive technologies announce validation errors depends on the UI framework and markup, not on the regex, and was not tested for this review.
Evidence gaps
No benchmark measurements, version-specific performance data or test results were supplied, so this review makes no claims about speed differences between static, instance, compiled and generated regexes beyond their documented design. No specific online regular expression validator was evaluated, so their accuracy against .NET and their data handling are unknown; avoid pasting real customer data or secrets into third-party testers unless their practices have been checked.
Bottom line
Regex.IsMatch with explicit ^ and \z anchors, a timeout for untrusted input, and a reused or generated Regex instance is a sound way to check whether a C# string matches a format. It reports shape only and never changes the input. Where the rule concerns a value's meaning, such as a real date, a number in range, a URL or an email address, a parser or plain string method gives a more reliable answer with less risk.