Regex 构造函数

定义

初始化 Regex 类的新实例。

重载

Regex()

初始化 Regex 类的新实例。

Regex(String)

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

Regex(SerializationInfo, StreamingContext)
已过时.

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

Regex(String, RegexOptions)

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

Regex(String, RegexOptions, TimeSpan)

使用修改模式的选项和指定在超时前多久模式匹配方法应进行匹配尝试的值为指定正则表达式初始化 Regex 类的新实例。

Regex()

初始化 Regex 类的新实例。

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

注解

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

适用于

Regex(String)

为指定的正则表达式初始化 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

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

例外

出现正则表达式分析错误。

patternnull

示例

下面的示例演示如何使用此构造函数来实例化与以字母“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)调用构造函数等效于调用Regex(String, RegexOptions)参数值为 的Noneoptions构造函数。

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

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

调用方说明

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

另请参阅

适用于

Regex(SerializationInfo, StreamingContext)

注意

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)

使用修改模式的选项为指定的正则表达式初始化 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

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

例外

出现正则表达式分析错误。

patternnull

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)

使用修改模式的选项和指定在超时前多久模式匹配方法应进行匹配尝试的值为指定正则表达式初始化 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

例外

出现正则表达式分析错误。

patternnull

options 不是有效的 RegexOptions 值。

- 或 -

matchTimeout 为负、零或大于 24 天左右。

示例

以下示例调用 Regex(String, RegexOptions, TimeSpan) 构造函数来实例化 Regex 超时值为 1 秒的 对象。 正则表达式模式 (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 适当的值,例如 2 秒。 如果通过指定 InfiniteMatchTimeout来禁用超时,则正则表达式引擎提供的性能稍好一些。 但是,应仅在以下情况下禁用超时:

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

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

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

另请参阅

适用于