Regex 构造函数

定义

初始化 Regex 类的新实例。

重载

Regex()

初始化 Regex 类的新实例。

Regex(String)

为指定的正则表达式初始化 Regex 类的新实例。

Regex(SerializationInfo, StreamingContext)
已过时.

使用序列化的数据初始化 Regex 类的新实例。

Regex(String, RegexOptions)

使用修改模式的选项初始化指定正则表达式的 Regex 类的新实例。

Regex(String, RegexOptions, TimeSpan)

为指定的正则表达式初始化 Regex 类的新实例,其中包含修改模式的选项和指定模式匹配方法在超时之前应尝试匹配的时间的值。

Regex()

Source:
Regex.cs
Source:
Regex.cs
Source:
Regex.cs

初始化 Regex 类的新实例。

protected:
 Regex();
protected Regex ();
Protected Sub New ()

注解

请注意,此构造函数受保护;它只能由派生自 Regex 类的类调用。

适用于

Regex(String)

Source:
Regex.cs
Source:
Regex.cs
Source:
Regex.cs

为指定的正则表达式初始化 Regex 类的新实例。

public:
 Regex(System::String ^ pattern);
public Regex (string pattern);
new System.Text.RegularExpressions.Regex : string -> System.Text.RegularExpressions.Regex
Public Sub New (pattern As String)

参数

pattern
String

要匹配的正则表达式模式。

例外

发生正则表达式分析错误。

pattern null

示例

下面的示例演示如何使用此构造函数实例化正则表达式,该正则表达式与以字母“a”或“t”开头的任何单词匹配。

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"\b[at]\w+";
      string text = "The threaded application ate up the thread pool as it executed.";
      MatchCollection matches;

      Regex defaultRegex = new Regex(pattern);
      // Get matches of pattern in text
      matches = defaultRegex.Matches(text);
      Console.WriteLine("Parsing '{0}'", text);
      // Iterate matches
      for (int ctr = 0; ctr < matches.Count; ctr++)
         Console.WriteLine("{0}. {1}", ctr, matches[ctr].Value);
   }
}
// The example displays the following output:
//       Parsing 'The threaded application ate up the thread pool as it executed.'
//       0. threaded
//       1. application
//       2. ate
//       3. the
//       4. thread
//       5. as
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim pattern As String = "\b[at]\w+"
      Dim text As String = "The threaded application ate up the thread pool as it executed."
      Dim matches As MatchCollection

      Dim defaultRegex As New Regex(pattern)
      ' Get matches of pattern in text
      matches = defaultRegex.Matches(text)
      Console.WriteLine("Parsing '{0}'", text)
      ' Iterate matches
      For ctr As Integer = 0 to matches.Count - 1
         Console.WriteLine("{0}. {1}", ctr, matches(ctr).Value)
      Next
   End Sub
End Module
' The example displays the following output:
'       Parsing 'The threaded application ate up the thread pool as it executed.'
'       0. threaded
'       1. application
'       2. ate
'       3. the
'       4. thread
'       5. as

请注意,正则表达式模式与文本开头的单词“The”不匹配,因为比较默认区分大小写。 有关不区分大小写的比较示例,请参阅 Regex(String, RegexOptions) 构造函数。

注解

警告

使用 处理不受信任的输入时, 传递 超时值,以防止恶意用户引发 拒绝服务攻击。 超时值指定模式匹配方法在超时之前应尝试查找匹配的时间。

pattern 参数由正则表达式语言元素组成,这些元素以符号方式描述要匹配的字符串。 有关正则表达式的详细信息,请参阅 .NET 正则表达式正则表达式语言 - 快速参考 主题。

调用 Regex(String) 构造函数等效于调用具有 options 参数 None 值的 Regex(String, RegexOptions) 构造函数。

Regex 对象是不可变的,这意味着它只能用于创建它时定义的匹配模式。 但是,可以在不重新编译的情况下使用任意次数。

此构造函数实例化正则表达式对象,该对象尝试对 pattern中定义的任何字母字符进行区分大小写的匹配。 对于不区分大小写的匹配,请使用 Regex.Regex(String, RegexOptions) 构造函数。

调用方说明

此构造函数创建一个 Regex 对象,该对象使用在其中创建应用程序域的默认超时值。 如果未为应用程序域定义超时值,Regex 对象将使用值 InfiniteMatchTimeout,从而阻止操作超时。用于创建 Regex 对象的推荐构造函数是 Regex(String, RegexOptions, TimeSpan),这使你可以设置超时间隔。

另请参阅

适用于

Regex(SerializationInfo, StreamingContext)

Source:
Regex.cs
Source:
Regex.cs
Source:
Regex.cs

注意

This API supports obsolete formatter-based serialization. It should not be called or extended by application code.

使用序列化的数据初始化 Regex 类的新实例。

protected:
 Regex(System::Runtime::Serialization::SerializationInfo ^ info, System::Runtime::Serialization::StreamingContext context);
protected Regex (System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context);
[System.Obsolete("This API supports obsolete formatter-based serialization. It should not be called or extended by application code.", DiagnosticId="SYSLIB0051", UrlFormat="https://aka.ms/dotnet-warnings/{0}")]
protected Regex (System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context);
new System.Text.RegularExpressions.Regex : System.Runtime.Serialization.SerializationInfo * System.Runtime.Serialization.StreamingContext -> System.Text.RegularExpressions.Regex
[<System.Obsolete("This API supports obsolete formatter-based serialization. It should not be called or extended by application code.", DiagnosticId="SYSLIB0051", UrlFormat="https://aka.ms/dotnet-warnings/{0}")>]
new System.Text.RegularExpressions.Regex : System.Runtime.Serialization.SerializationInfo * System.Runtime.Serialization.StreamingContext -> System.Text.RegularExpressions.Regex
Protected Sub New (info As SerializationInfo, context As StreamingContext)

参数

info
SerializationInfo

包含序列化模式和 RegexOptions 信息的对象。

context
StreamingContext

此序列化的目标。 (未使用此参数;指定 null.)

属性

例外

发生正则表达式分析错误。

info 包含的模式为 null

info 包含无效的 RegexOptions 标志。

适用于

Regex(String, RegexOptions)

Source:
Regex.cs
Source:
Regex.cs
Source:
Regex.cs

使用修改模式的选项初始化指定正则表达式的 Regex 类的新实例。

public:
 Regex(System::String ^ pattern, System::Text::RegularExpressions::RegexOptions options);
public Regex (string pattern, System.Text.RegularExpressions.RegexOptions options);
new System.Text.RegularExpressions.Regex : string * System.Text.RegularExpressions.RegexOptions -> System.Text.RegularExpressions.Regex
Public Sub New (pattern As String, options As RegexOptions)

参数

pattern
String

要匹配的正则表达式模式。

options
RegexOptions

修改正则表达式的枚举值的按位组合。

例外

发生正则表达式分析错误。

pattern null

options 包含无效标志。

示例

下面的示例演示如何使用此构造函数实例化正则表达式,该正则表达式与以字母“a”或“t”开头的任何单词匹配。

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"\b[at]\w+";
      RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Compiled;
      string text = "The threaded application ate up the thread pool as it executed.";
      MatchCollection matches;

      Regex optionRegex = new Regex(pattern, options);
      Console.WriteLine("Parsing '{0}' with options {1}:", text, options.ToString());
      // Get matches of pattern in text
      matches = optionRegex.Matches(text);
      // Iterate matches
      for (int ctr = 0; ctr < matches.Count; ctr++)
         Console.WriteLine("{0}. {1}", ctr, matches[ctr].Value);
   }
}
// The example displays the following output:
//    Parsing 'The threaded application ate up the thread pool as it executed.'
//        with options IgnoreCase, Compiled:
//    0. The
//    1. threaded
//    2. application
//    3. ate
//    4. the
//    5. thread
//    6. as
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim pattern As String = "\b[at]\w+"
      Dim options As RegexOptions = RegexOptions.IgnoreCase Or RegexOptions.Compiled
      Dim text As String = "The threaded application ate up the thread pool as it executed."
      Dim matches As MatchCollection

      Dim optionRegex As New Regex(pattern, options)
      Console.WriteLine("Parsing '{0}' with options {1}:", text, options.ToString())
      ' Get matches of pattern in text
      matches = optionRegex.Matches(text)
      ' Iterate matches   
      For ctr As Integer = 0 to matches.Count - 1
         Console.WriteLine("{0}. {1}", ctr, matches(ctr).Value)
      Next
   End Sub
End Module
' The example displays the following output:
'    Parsing 'The threaded application ate up the thread pool as it executed.'
'       with options IgnoreCase, Compiled:
'    0. The
'    1. threaded
'    2. application
'    3. ate
'    4. the
'    5. thread
'    6. as

请注意,匹配集合包含以文本开头的单词“The”,因为 options 参数定义了不区分大小写的比较。

注解

警告

使用 处理不受信任的输入时, 传递 超时值,以防止恶意用户引发 拒绝服务攻击。 超时值指定模式匹配方法在超时之前应尝试查找匹配的时间。

pattern 参数由正则表达式语言元素组成,这些元素以符号方式描述要匹配的字符串。 有关正则表达式的详细信息,请参阅 .NET 正则表达式正则表达式语言 - 快速参考 主题。

Regex 对象是不可变的,这意味着它只能用于创建对象时定义的匹配参数。 但是,可以在不重新编译的情况下使用任意次数。

调用方说明

此构造函数创建一个 Regex 对象,该对象使用在其中创建应用程序域的默认超时值。 如果未为应用程序域定义超时值,Regex 对象将使用值 InfiniteMatchTimeout,从而阻止操作超时。用于创建 Regex 对象的推荐构造函数是 Regex(String, RegexOptions, TimeSpan),这使你可以设置超时间隔。

另请参阅

适用于

Regex(String, RegexOptions, TimeSpan)

Source:
Regex.cs
Source:
Regex.cs
Source:
Regex.cs

为指定的正则表达式初始化 Regex 类的新实例,其中包含修改模式的选项和指定模式匹配方法在超时之前应尝试匹配的时间的值。

public:
 Regex(System::String ^ pattern, System::Text::RegularExpressions::RegexOptions options, TimeSpan matchTimeout);
public Regex (string pattern, System.Text.RegularExpressions.RegexOptions options, TimeSpan matchTimeout);
new System.Text.RegularExpressions.Regex : string * System.Text.RegularExpressions.RegexOptions * TimeSpan -> System.Text.RegularExpressions.Regex
Public Sub New (pattern As String, options As RegexOptions, matchTimeout As TimeSpan)

参数

pattern
String

要匹配的正则表达式模式。

options
RegexOptions

修改正则表达式的枚举值的按位组合。

matchTimeout
TimeSpan

超时间隔,或 InfiniteMatchTimeout 指示方法不应超时。

例外

发生正则表达式分析错误。

pattern null

options 不是有效的 RegexOptions 值。

-或-

matchTimeout 为负数、零或大于约 24 天。

示例

以下示例调用 Regex(String, RegexOptions, TimeSpan) 构造函数,以实例化具有一秒超时值 Regex 对象。 正则表达式模式 (a+)+$,该模式与一行末尾的一个或多个“a”字符的一个或多个序列匹配,因此会进行过度回溯。 如果引发 RegexMatchTimeoutException,该示例将超时值增加到 3 秒的最大值。 否则,它会放弃与模式匹配的尝试。

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",
                         "aaaaaaaaaaaaaaaaaaaaaa>",
                         "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)) {
                  sw.Stop();
                  Console.WriteLine(@"Valid: '{0}' ({1:ss\.fffffff} seconds)", 
                                    inputValue, sw.Elapsed); 
               }
               else {
                  sw.Stop();
                  Console.WriteLine(@"'{0}' is not a valid string. ({1:ss\.fffff} seconds)", 
                                    inputValue, sw.Elapsed);
               }
            }
            catch (RegexMatchTimeoutException e) {   
               sw.Stop();
               // 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.",
                                    MaxTimeoutInSeconds);
                  timedOut = false;
               }
               else {               
                  Console.WriteLine("Changing the timeout interval to {0}", 
                                    timeout); 
                  rgx = new Regex(pattern, RegexOptions.IgnoreCase, timeout);
                  timedOut = true;
               }
            }
         } while (timedOut);
         Console.WriteLine();
      }   
   }
}
// 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.
Imports System.ComponentModel
Imports System.Diagnostics
Imports System.Security
Imports System.Text.RegularExpressions
Imports System.Threading 

Module Example
   Const MaxTimeoutInSeconds As Integer = 3
   
   Public Sub Main()
      Dim pattern As String = "(a+)+$"    ' DO NOT REUSE THIS PATTERN.
      Dim rgx As New Regex(pattern, RegexOptions.IgnoreCase, TimeSpan.FromSeconds(1))       
      Dim sw As Stopwatch = Nothing
      
      Dim inputs() As String = { "aa", "aaaa>", 
                                 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                                 "aaaaaaaaaaaaaaaaaaaaaa>",
                                 "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>" }
                                 
      For Each inputValue In inputs
         Console.WriteLine("Processing {0}", inputValue)
         Dim timedOut As Boolean = False
         Do 
            Try
               sw = Stopwatch.StartNew()
               ' Display the result.
               If rgx.IsMatch(inputValue) Then
                  sw.Stop()
                  Console.WriteLine("Valid: '{0}' ({1:ss\.fffffff} seconds)", 
                                    inputValue, sw.Elapsed) 
               Else
                  sw.Stop()
                  Console.WriteLine("'{0}' is not a valid string. ({1:ss\.fffff} seconds)", 
                                    inputValue, sw.Elapsed)
               End If
            Catch e As RegexMatchTimeoutException   
               sw.Stop()
               ' 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.
               Dim timeout As TimeSpan = e.MatchTimeout.Add(TimeSpan.FromSeconds(1))
               If timeout.TotalSeconds > MaxTimeoutInSeconds Then
                  Console.WriteLine("Maximum timeout interval of {0} seconds exceeded.",
                                    MaxTimeoutInSeconds)
                  timedOut = False
               Else                
                  Console.WriteLine("Changing the timeout interval to {0}", 
                                    timeout) 
                  rgx = New Regex(pattern, RegexOptions.IgnoreCase, timeout)
                  timedOut = True
               End If
            End Try
         Loop While timedOut
         Console.WriteLine()
      Next   
   End Sub 
End Module
' 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.

注解

pattern 参数由正则表达式语言元素组成,这些元素以符号方式描述要匹配的字符串。 有关正则表达式的详细信息,请参阅 .NET 正则表达式正则表达式语言 - 快速参考 主题。

Regex 对象是不可变的,这意味着它只能用于创建它时定义的匹配模式。 但是,可以在不重新编译的情况下使用任意次数。

matchTimeout 参数指定模式匹配方法在超时之前应尝试查找匹配项的时间。如果未在该时间间隔中找到匹配项,则模式匹配方法将引发 RegexMatchTimeoutException 异常。 matchTimeout 替代为创建 Regex 对象的应用程序域定义的任何默认超时值。 观察 matchTimeout 超时间隔的实例模式匹配方法包括:

设置超时间隔可防止依赖过度回溯的正则表达式在处理包含接近匹配项的输入时停止响应。 有关详细信息,请参阅 正则表达式的最佳做法回溯。 若要设置合理的超时间隔,请考虑以下因素:

  • 正则表达式模式的长度和复杂性。 较长且更复杂的正则表达式需要比更短、更简单的正则表达式更长的时间。

  • 预期的计算机负载。 处理在 CPU 和内存利用率较高的系统上需要更多时间。

调用方说明

建议将 matchTimeout 参数设置为适当的值,例如两秒。 如果通过指定 InfiniteMatchTimeout来禁用超时,则正则表达式引擎提供略微更好的性能。 但是,应仅在以下情况下禁用超时:

  • 当正则表达式处理的输入派生自已知且受信任的源或包含静态文本时。 这不包括用户动态输入的文本。

  • 当正则表达式模式经过全面测试以确保它有效地处理匹配项、非匹配项和接近匹配项时。

  • 当正则表达式模式不包含任何已知在处理接近匹配时导致过度回溯的语言元素。

另请参阅

适用于