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 具有一秒逾時值的物件。 規則運算式模式 (a+)+$ 會在行尾比對一個或多個 "a" 字元的一個或多個序列,並且受限於大量回溯。 RegexMatchTimeoutException如果擲回 ,此範例會將逾時值增加至最多三秒的最大值。 否則,它會放棄嘗試比對模式。

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 來停用逾時,正則運算式引擎會提供稍微更好的效能。 不過,您應該只在下列情況下停用逾時:

  • 當正則運算式處理的輸入衍生自已知且受信任的來源,或由靜態文字所組成時。 這會排除使用者動態輸入的文字。

  • 當正則運算式模式經過徹底測試,以確保它可以有效率地處理相符專案、非相符專案和接近相符專案。

  • 當正則運算式模式不包含已知在處理接近相符專案時造成過度回溯的語言專案時。

另請參閱

適用於