Export (0) Print
Expand All
1 out of 1 rated this helpful - Rate this topic

Regex Constructor (String, RegexOptions, TimeSpan)

.NET Framework 4.5

Initializes a new instance of the Regex class for the specified regular expression, with options that modify the pattern and a value that specifies how long a pattern matching method should attempt a match before it times out.

Namespace:  System.Text.RegularExpressions
Assembly:  System (in System.dll)
public Regex(
	string pattern,
	RegexOptions options,
	TimeSpan matchTimeout


Type: System.String

The regular expression pattern to match.

Type: System.Text.RegularExpressions.RegexOptions

A bitwise combination of the enumeration values that modify the regular expression.

Type: System.TimeSpan



A regular expression parsing error occurred.


pattern is null.


options is not a valid RegexOptions value.



The pattern parameter consists of regular expression language elements that symbolically describe the string to match. For more information about regular expressions, see the .NET Framework Regular Expressions and Regular Expression Language - Quick Reference topics.

A Regex object is immutable, which means that it can be used only for the match pattern that you define when you create it. However, it can be used any number of times without being recompiled.

The matchTimeout parameter specifies how long a pattern-matching method should try to find a match before it times out. If no match is found in that time interval, the pattern-matching method throws a RegexMatchTimeoutException exception. matchTimeout overrides any default time-out value defined for the application domain in which the Regex object is created. The instance pattern-matching methods that observe the matchTimeout time-out interval include the following:

Setting a time-out interval prevents regular expressions that rely on excessive backtracking from appearing to stop responding when they process input that contains near matches. For more information, see Best Practices for Regular Expressions in the .NET Framework and Backtracking. To set a reasonable time-out interval, consider the following factors:

  • The length and complexity of the regular expression pattern. Longer and more complex regular expressions require more time than shorter and simpler ones.

  • The expected machine load. Processing takes more time on systems that have high CPU and memory utilization.

Notes to Callers





The following example calls the Regex(String, RegexOptions, TimeSpan) constructor to instantiate a Regex object with a time-out value of one second. The regular expression pattern (a+)+$, which matches one or more sequences of one or more "a" characters at the end of a line, is subject to excessive backtracking. If a RegexMatchTimeoutException is thrown, the example increases the time-out value up to the maximum value of three seconds. Otherwise, it abandons the attempt to match the pattern.

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Security;
using System.Text.RegularExpressions;
using System.Threading; 

public class Example
   const int MaxTimeoutInSeconds = 3;

   public static void Main()
      string pattern = @"(a+)+$";    // DO NOT REUSE THIS PATTERN.
      Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase, TimeSpan.FromSeconds(1));       
      Stopwatch sw = null;

      string[] inputs= { "aa", "aaaa>", 
                         "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>" };

      foreach (var inputValue in inputs) {
         Console.WriteLine("Processing {0}", inputValue);
         bool timedOut = false;
         do { 
            try {
               sw = Stopwatch.StartNew();
               // Display the result. 
               if (rgx.IsMatch(inputValue)) {
                  Console.WriteLine(@"Valid: '{0}' ({1:ss\.fffffff} seconds)", 
                                    inputValue, sw.Elapsed); 
               else {
                  Console.WriteLine(@"'{0}' is not a valid string. ({1:ss\.fffff} seconds)", 
                                    inputValue, sw.Elapsed);
            catch (RegexMatchTimeoutException e) {   
               // Display the elapsed time until the exception.
               Console.WriteLine(@"Timeout with '{0}' after {1:ss\.fffff}", 
                                 inputValue, sw.Elapsed);
               Thread.Sleep(1500);       // Pause for 1.5 seconds. 

               // Increase the timeout interval and retry.
               TimeSpan timeout = e.MatchTimeout.Add(TimeSpan.FromSeconds(1));
               if (timeout.TotalSeconds > MaxTimeoutInSeconds) {
                  Console.WriteLine("Maximum timeout interval of {0} seconds exceeded.",
                  timedOut = false;
               else {               
                  Console.WriteLine("Changing the timeout interval to {0}", 
                  rgx = new Regex(pattern, RegexOptions.IgnoreCase, timeout);
                  timedOut = true;
         } while (timedOut);
// The example displays output like the following : 
//    Processing aa 
//    Valid: 'aa' (00.0000779 seconds) 
//    Processing aaaa> 
//    'aaaa>' is not a valid string. (00.00005 seconds) 
//    Processing aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 
//    Valid: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' (00.0000043 seconds) 
//    Processing aaaaaaaaaaaaaaaaaaaaaa> 
//    Timeout with 'aaaaaaaaaaaaaaaaaaaaaa>' after 01.00469 
//    Changing the timeout interval to 00:00:02 
//    Timeout with 'aaaaaaaaaaaaaaaaaaaaaa>' after 02.01202 
//    Changing the timeout interval to 00:00:03 
//    Timeout with 'aaaaaaaaaaaaaaaaaaaaaa>' after 03.01043 
//    Maximum timeout interval of 3 seconds exceeded. 
//    Processing aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> 
//    Timeout with 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>' after 03.01018 
//    Maximum timeout interval of 3 seconds exceeded.

.NET Framework

Supported in: 4.5.1, 4.5

.NET for Windows Store apps

Supported in: Windows 8



Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
© 2014 Microsoft. All rights reserved.