RegexCompilationInfo.MatchTimeout Propiedad

Definición

Obtiene o establece el intervalo de tiempo de espera predeterminado de la expresión regular.

public:
 property TimeSpan MatchTimeout { TimeSpan get(); void set(TimeSpan value); };
public TimeSpan MatchTimeout { get; set; }
member this.MatchTimeout : TimeSpan with get, set
Public Property MatchTimeout As TimeSpan

Valor de propiedad

Intervalo de tiempo máximo predeterminado que puede transcurrir en una operación de coincidencia de modelos antes de que se produzca una RegexMatchTimeoutException o InfiniteMatchTimeout si se deshabilitan los tiempos de espera.

Ejemplos

En el ejemplo siguiente se define una única expresión regular compilada denominada DuplicateChars que identifica dos o más apariciones del mismo carácter en una cadena de entrada. La expresión regular compilada tiene un tiempo de espera predeterminado de 2 segundos. Al ejecutar el ejemplo, crea una biblioteca de clases denominada RegexLib.dll que contiene la expresión regular compilada.

using System;
using System.Reflection;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
        // Match two or more occurrences of the same character.
        string pattern = @"(\w)\1+";
        
        // Use case-insensitive matching. 
        var rci = new RegexCompilationInfo(pattern, RegexOptions.IgnoreCase,
                                           "DuplicateChars", "CustomRegexes", 
                                           true, TimeSpan.FromSeconds(2));

        // Define an assembly to contain the compiled regular expression.
        var an = new AssemblyName();
        an.Name = "RegexLib";
        RegexCompilationInfo[] rciList = { rci };

        // Compile the regular expression and create the assembly.
        Regex.CompileToAssembly(rciList, an);
   }
}
Imports System.Reflection
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
        ' Match two or more occurrences of the same character.
        Dim pattern As String = "(\w)\1+"
        
        ' Use case-insensitive matching. 
        Dim rci As New RegexCompilationInfo(pattern, RegexOptions.IgnoreCase,
                                            "DuplicateChars", "CustomRegexes", 
                                            True, TimeSpan.FromSeconds(2))

        ' Define an assembly to contain the compiled regular expression.
        Dim an As New AssemblyName()
        an.Name = "RegexLib"
        Dim rciList As RegexCompilationInfo() = New RegexCompilationInfo() { rci }

        ' Compile the regular expression and create the assembly.
        Regex.CompileToAssembly(rciList, an)
   End Sub
End Module

El patrón de expresión regular (\w)\1+ se define como se muestra en la tabla siguiente.

Modelo Descripción
(\w) Coincide con cualquier carácter de palabra y asígnelo al primer grupo de captura.
\1+ Coincide con una o varias repeticiones del valor del primer grupo capturado.

En el ejemplo siguiente se usa la DuplicatedChars expresión regular para identificar caracteres duplicados en una matriz de cadenas. Cuando llama al DuplicatedChars constructor, cambia el intervalo de tiempo de espera a .5 segundos.

using CustomRegexes;
using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      var rgx = new DuplicateChars(TimeSpan.FromSeconds(.5));
      
      string[] values = { "Greeeeeat", "seed", "deed", "beam", 
                          "loop", "Aardvark" };
      // Display regex information.
      Console.WriteLine("Regular Expression Pattern: {0}", rgx);
      Console.WriteLine("Regex timeout value: {0} seconds\n", 
                        rgx.MatchTimeout.TotalSeconds);
      
      // Display matching information.
      foreach (var value in values) {
         Match m = rgx.Match(value);
         if (m.Success)
            Console.WriteLine("'{0}' found in '{1}' at positions {2}-{3}",
                              m.Value, value, m.Index, m.Index + m.Length - 1);
         else
            Console.WriteLine("No match found in '{0}'", value);
      }                                                         
   }
}
// The example displays the following output:
//       Regular Expression Pattern: (\w)\1+
//       Regex timeout value: 0.5 seconds
//       
//       //eeeee// found in //Greeeeeat// at positions 2-6
//       //ee// found in //seed// at positions 1-2
//       //ee// found in //deed// at positions 1-2
//       No match found in //beam//
//       //oo// found in //loop// at positions 1-2
//       //Aa// found in //Aardvark// at positions 0-1
Imports CustomRegexes
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim rgx As New DuplicateChars(TimeSpan.FromSeconds(.5))
      
      Dim values() As String = { "Greeeeeat", "seed", "deed", "beam", 
                                 "loop", "Aardvark" }
      ' Display regex information.
      Console.WriteLine("Regular Expression Pattern: {0}", rgx)
      Console.WriteLine("Regex timeout value: {0} seconds", 
                        rgx.MatchTimeout.TotalSeconds)
      Console.WriteLine()
      
      ' Display matching information.
      For Each value In values
         Dim m As Match = rgx.Match(value)
         If m.Success Then
            Console.WriteLine("'{0}' found in '{1}' at positions {2}-{3}",
                              m.Value, value, m.Index, m.Index + m.Length - 1)
         Else
            Console.WriteLine("No match found in '{0}'", value)
         End If   
      Next                                                         
   End Sub
End Module
' The example displays the following output:
'       Regular Expression Pattern: (\w)\1+
'       Regex timeout value: 0.5 seconds
'       
'       'eeeee' found in 'Greeeeeat' at positions 2-6
'       'ee' found in 'seed' at positions 1-2
'       'ee' found in 'deed' at positions 1-2
'       No match found in 'beam'
'       'oo' found in 'loop' at positions 1-2
'       'Aa' found in 'Aardvark' at positions 0-1

Comentarios

La MatchTimeout propiedad define el intervalo de tiempo de espera predeterminado para la expresión regular compilada. Este valor representa la cantidad aproximada de tiempo que una expresión regular compilada ejecutará una única operación coincidente antes de que se agote el tiempo de espera de la operación y el motor de expresiones regulares inicia una RegexMatchTimeoutException excepción durante su siguiente comprobación de tiempo.

Importante

Se recomienda establecer siempre un valor de tiempo de espera predeterminado para una expresión regular compilada. Los consumidores de la biblioteca de expresiones regulares pueden invalidar ese valor de tiempo de espera pasando un TimeSpan valor que representa el nuevo intervalo de tiempo de espera al constructor de clase de la expresión regular compilada.

Puede asignar un valor de tiempo de espera predeterminado a un RegexCompilationInfo objeto de cualquiera de las siguientes maneras:

Para establecer un intervalo de tiempo de espera razonable, tenga en cuenta los siguientes factores:

  • Longitud y complejidad del patrón de expresión regular. Las expresiones regulares más largas y complejas requieren más tiempo que las más cortas y más sencillas.

  • Carga esperada de la máquina. El procesamiento tarda más tiempo en los sistemas con un uso elevado de CPU y memoria.

Se aplica a

Consulte también