C# validate regex pattern
How to check that a regular expression pattern is valid in C#: what parsing catches, what it misses, how options and engine dialects affect results, and copy/paste pitfalls.
Short answer: when pattern validation in C# is worth doing
Validate patterns before use if your application accepts them from users, configuration files or other sources you don't control. The usual approach is to construct a Regex inside a try/catch block and set a match timeout. The main benefit is that you catch a malformed pattern where it enters the system, with a specific error, instead of getting an unhandled exception later. The key tradeoff is that a successful parse only proves the .NET engine accepts the syntax. It doesn't show that the pattern matches what you intend, or that it runs safely on hostile input. If the pattern is a fixed literal in your own code, runtime validation adds little, and build-time checking or a unit test is a better fit. If users only need to search for literal text, plain string methods or an escaped pattern are simpler and safer than accepting arbitrary regex syntax.
Two different meanings of "validate a regex"
The phrase can mean two different tasks. The first is checking that the pattern string itself is syntactically valid for the .NET regex engine, which is the subject of this article. The second is using a pattern to check input, such as calling Regex.IsMatch to test whether an email field looks correct. The second task assumes the first has already succeeded. Mixing the two up leads to code that tests input against a pattern that was never confirmed to parse.
What validation actually checks, and what it changes
In .NET, the pattern is parsed when a Regex object is constructed. The static helpers such as Regex.IsMatch also parse it on first use. An invalid pattern causes an ArgumentException. Starting with .NET 7, the thrown type is RegexParseException, which derives from ArgumentException and exposes an Error value describing the problem and an Offset indicating where in the pattern it was found. Validation does not modify the pattern: the stored characters stay exactly as supplied. The only common operation that changes the characters is Regex.Escape. It inserts backslashes so that metacharacters are treated as literal text, which turns a regex pattern into a literal search.
using System;
using System.Text.RegularExpressions;
static bool TryValidatePattern(string pattern, RegexOptions options, out string? error)
{
try
{
_ = new Regex(pattern, options, TimeSpan.FromSeconds(1));
error = null;
return true;
}
catch (RegexParseException ex) // .NET 7 and later
{
error = $"{ex.Error} at offset {ex.Offset}";
return false;
}
catch (ArgumentException ex) // older runtimes, null pattern, invalid options
{
error = ex.Message;
return false;
}
catch (NotSupportedException ex) // construct not supported by the chosen options
{
error = ex.Message;
return false;
}
}
Validate with the same RegexOptions you will use in production, because options affect what is accepted. RegexOptions.NonBacktracking, available from .NET 7, rejects constructs that depend on backtracking, such as backreferences, lookarounds and atomic groups. A pattern that parses under default options can therefore fail under NonBacktracking. RegexOptions.ECMAScript can only be combined with certain other options, and it changes how some constructs are interpreted. On runtimes older than .NET 7, RegexParseException is not available, so remove that catch clause and rely on ArgumentException. The timeout passed to the constructor governs matching, not parsing, but setting it at the point of validation keeps the validated object safe to reuse.
Build-time checking with the regex source generator
For patterns known when you write the code, .NET 7 and later provide the GeneratedRegex attribute. The source generator parses the pattern during compilation and reports an invalid pattern as a build diagnostic, so the error appears in the IDE or build output instead of at run time. This approach does not apply to patterns that arrive at run time, which still need the try/catch approach.
using System.Text.RegularExpressions;
public static partial class Patterns
{
[GeneratedRegex(@"^\d{3}-\d{4}$")]
public static partial Regex PhoneSuffix();
}
Comparing the approaches
| Approach | When it detects errors | Suitable for | Main limitation |
| Construct Regex in try/catch | At run time, when the pattern is supplied | User input, configuration, stored patterns | Confirms syntax only; must use production options |
| GeneratedRegex source generator | At build time | Fixed patterns in source code | Not usable for patterns supplied at run time |
| Unit tests with sample inputs | When tests run | Confirming the pattern matches intended text | Only as good as the chosen samples |
| Regex.Escape instead of validation | Not applicable; no regex syntax is accepted | Literal text search | Users lose access to regex features |
Will the pattern survive copying and sharing?
String literal escaping is the most frequent copy/paste problem. A pattern such as \d+ pasted into a regular C# string literal does not compile, because \d is not a valid C# escape sequence. You can double each backslash, use a verbatim string prefixed with @, or use a raw string literal (C# 11 and later), which keeps the pattern as written. When copying in the other direction, from C# source into a regex tester, undo the C# escaping first. A doubled backslash in a regular literal is one backslash in the actual pattern, and a doubled quote in a verbatim string is one quote.
Text copied from documents, chat messages or web pages can carry characters that look ordinary but aren't. Examples include non-breaking spaces, zero-width characters, and curly quotes in place of straight ones. The parser accepts all of these as literal characters, so the pattern passes validation and then fails to match the expected text. If a validated pattern behaves unexpectedly, inspect its code points rather than its rendered appearance.
Regex dialects are not interchangeable. A pattern that works in a JavaScript, PCRE or Python tester can fail or behave differently in .NET. The /pattern/flags delimiters used in JavaScript are not part of a .NET pattern string. Python's (?P<name>...) named-group syntax is not supported; .NET uses (?<name>...) or (?'name'...). Possessive quantifiers such as a++ are rejected by the .NET parser. In the other direction, .NET-specific features such as balancing groups won't carry over to other engines. To get reliable results, test with a tool that uses the .NET engine, or validate in code against the target runtime.
If you show validation results to users in an interface, present the error as text, including the position, rather than relying on color or highlighting alone. Base program logic on the Error and Offset values, not on the exception message, whose wording can vary between runtime versions and installed language resources. This article did not test any particular screen reader or online regex tool, so no claims are made about how a specific product announces or displays these errors.
Limits that syntax validation does not cover
- Intent: a valid pattern can still match too much or too little, so test it against representative positive and negative samples.
- Performance: a valid pattern can backtrack excessively on crafted input, so set a match timeout and handle RegexMatchTimeoutException, or consider NonBacktracking where its restrictions are acceptable.
- Culture: case-insensitive matching can depend on culture settings, so add RegexOptions.CultureInvariant when results must be consistent across environments.
- Trust: accepting arbitrary patterns from untrusted users exposes matching cost even after validation, so restrict who can supply patterns or limit what they can do.
What this review could not verify
No product-specific evidence, benchmarks or test results were provided for this review, so it contains no performance figures, tool comparisons or measured error rates. The behavior described here reflects documented .NET regex behavior. Because exception types and supported options have changed between versions, confirm the details against the framework version your project targets.