Codectionary / Developer documentation / C#

Regex Validation with Timeouts

Regex matches and extracts structured text. A timeout bounds matching time for patterns that may backtrack; handle timeout failures separately from a normal nonmatch. Use a .NET 8+ console project; replace Program.cs with this C# example.

Read the syntax

Regex matches and extracts structured text. A timeout bounds matching time for patterns that may backtrack; handle timeout failures separately from a normal nonmatch. Use a .NET 8+ console project; replace Program.cs with this C# example.

The absolute anchors require the full string to match. Named groups extract the validated prefix and numeric identifier.

Syntax

new Regex(pattern, RegexOptions.None, TimeSpan.FromMilliseconds(100))

Examples

Regex Validation with Timeouts

Use a .NET 8+ console project; replace Program.cs with this C# example.

using System;
using System.Text.RegularExpressions;
var pattern = new Regex(@"\A(?<kind>[A-Z]+)-(?<number>[0-9]{3})\z",
    RegexOptions.None, TimeSpan.FromMilliseconds(100));
Match match = pattern.Match("TASK-042");
if (match.Success)
    Console.WriteLine($"{match.Groups["kind"].Value} {int.Parse(match.Groups["number"].Value)}");
Console.WriteLine(pattern.IsMatch("TASK-042-extra"));
  1. Expected output: TASK 42 False
  2. The absolute anchors require the full string to match. Named groups extract the validated prefix and numeric identifier.
  3. Set a timeout for regex evaluation over untrusted input and handle RegexMatchTimeoutException.

Best practices

  • Set a timeout for regex evaluation over untrusted input and handle RegexMatchTimeoutException.
  • Use a parser instead of increasingly complex regexes for nested languages.

Runtime & versions

.NET runtime. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

C# language reference

Specifications & further reading