Regex 類別

定義

表示不變的規則運算式 (Regular Expression)。Represents an immutable regular expression.

public ref class Regex
public ref class Regex : System::Runtime::Serialization::ISerializable
public class Regex
public class Regex : System.Runtime.Serialization.ISerializable
[System.Serializable]
public class Regex : System.Runtime.Serialization.ISerializable
type Regex = class
type Regex = class
    interface ISerializable
[<System.Serializable>]
type Regex = class
    interface ISerializable
Public Class Regex
Public Class Regex
Implements ISerializable
繼承
Regex
衍生
屬性
實作

範例

下列範例會使用正則運算式來檢查字串中是否有重複出現的文字。The following example uses a regular expression to check for repeated occurrences of words in a string. 正則運算式 \b(?<word>\w+)\s+(\k<word>)\b 可以如下表所示進行解讀。The regular expression \b(?<word>\w+)\s+(\k<word>)\b can be interpreted as shown in the following table.

模式Pattern 描述Description
\b 在字邊界開始比對。Start the match at a word boundary.
(?<word>\w+) 比對一或多個文字字元到單字界限。Match one or more word characters up to a word boundary. 命名此已捕獲群組 wordName this captured group word.
\s+ 符合一或多個空白字元。Match one or more white-space characters.
(\k<word>) 符合名為的已捕獲群組 wordMatch the captured group that is named word.
\b 比對字邊界。Match a word boundary.
#using <System.dll>

using namespace System;
using namespace System::Text::RegularExpressions;
int main()
{
   // Define a regular expression for repeated words.
   Regex^ rx = gcnew Regex( "\\b(?<word>\\w+)\\s+(\\k<word>)\\b",static_cast<RegexOptions>(RegexOptions::Compiled | RegexOptions::IgnoreCase) );

   // Define a test string.        
   String^ text = "The the quick brown fox  fox jumps over the lazy dog dog.";

   // Find matches.
   MatchCollection^ matches = rx->Matches( text );

   // Report the number of matches found.
   Console::WriteLine( "{0} matches found.", matches->Count );

   // Report on each match.
   for each (Match^ match in matches)
   {
      String^ word = match->Groups["word"]->Value;
      int index = match->Index;
      Console::WriteLine("{0} repeated at position {1}", word, index);   
   }
}
using System;
using System.Text.RegularExpressions;

public class Test
{

    public static void Main ()
    {

        // Define a regular expression for repeated words.
        Regex rx = new Regex(@"\b(?<word>\w+)\s+(\k<word>)\b",
          RegexOptions.Compiled | RegexOptions.IgnoreCase);

        // Define a test string.
        string text = "The the quick brown fox  fox jumps over the lazy dog dog.";

        // Find matches.
        MatchCollection matches = rx.Matches(text);

        // Report the number of matches found.
        Console.WriteLine("{0} matches found in:\n   {1}",
                          matches.Count,
                          text);

        // Report on each match.
        foreach (Match match in matches)
        {
            GroupCollection groups = match.Groups;
            Console.WriteLine("'{0}' repeated at positions {1} and {2}",
                              groups["word"].Value,
                              groups[0].Index,
                              groups[1].Index);
        }
    }
}
// The example produces the following output to the console:
//       3 matches found in:
//          The the quick brown fox  fox jumps over the lazy dog dog.
//       'The' repeated at positions 0 and 4
//       'fox' repeated at positions 20 and 25
//       'dog' repeated at positions 50 and 54
Imports System.Text.RegularExpressions

Public Module Test

    Public Sub Main()
        ' Define a regular expression for repeated words.
        Dim rx As New Regex("\b(?<word>\w+)\s+(\k<word>)\b", _
               RegexOptions.Compiled Or RegexOptions.IgnoreCase)

        ' Define a test string.        
        Dim text As String = "The the quick brown fox  fox jumps over the lazy dog dog."
        
        ' Find matches.
        Dim matches As MatchCollection = rx.Matches(text)

        ' Report the number of matches found.
        Console.WriteLine("{0} matches found in:", matches.Count)
        Console.WriteLine("   {0}", text)

        ' Report on each match.
        For Each match As Match In matches
            Dim groups As GroupCollection = match.Groups
            Console.WriteLine("'{0}' repeated at positions {1} and {2}", _ 
                              groups.Item("word").Value, _
                              groups.Item(0).Index, _
                              groups.Item(1).Index)
        Next
    End Sub
End Module
' The example produces the following output to the console:
'       3 matches found in:
'          The the quick brown fox  fox jumps over the lazy dog dog.
'       'The' repeated at positions 0 and 4
'       'fox' repeated at positions 20 and 25
'       'dog' repeated at positions 50 and 54

下列範例說明如何使用正則運算式來檢查字串是否代表貨幣值,或是否具有正確的格式來表示貨幣值。The following example illustrates the use of a regular expression to check whether a string either represents a currency value or has the correct format to represent a currency value. 在此情況下,正則運算式是從 NumberFormatInfo.CurrencyDecimalSeparator CurrencyDecimalDigits NumberFormatInfo.CurrencySymbol NumberFormatInfo.NegativeSign NumberFormatInfo.PositiveSign 使用者目前文化特性的、、、和屬性動態建立。In this case, the regular expression is built dynamically from the NumberFormatInfo.CurrencyDecimalSeparator, CurrencyDecimalDigits, NumberFormatInfo.CurrencySymbol, NumberFormatInfo.NegativeSign, and NumberFormatInfo.PositiveSign properties for the user's current culture. 如果系統目前的文化特性是 en-us,則產生的正則運算式為 ^\s*[\+-]?\s?\$?\s?(\d*\.?\d{2}?){1}$If the system's current culture is en-US, the resulting regular expression is ^\s*[\+-]?\s?\$?\s?(\d*\.?\d{2}?){1}$. 此正則運算式可以如下表所示加以解讀。This regular expression can be interpreted as shown in the following table.

模式Pattern 描述Description
^ 從字串的開頭開始。Start at the beginning of the string.
\s* 比對零個以上的空白字元。Match zero or more white-space characters.
[\+-]? 符合零次或一次出現正負號或負號。Match zero or one occurrence of either the positive sign or the negative sign.
\s? 比對零個或一個空白字元。Match zero or one white-space character.
\$? 符合零次或一次出現的貨幣符號。Match zero or one occurrence of the dollar sign.
\s? 比對零個或一個空白字元。Match zero or one white-space character.
\d* 比對零個或多個十進位數字。Match zero or more decimal digits.
\.? 符合零或一個小數點符號。Match zero or one decimal point symbol.
\d{2}? 比對兩個小數位數零或一次。Match two decimal digits zero or one time.
(\d*\.?\d{2}?){1} 比對整數和小數位數的模式,並以小數點符號至少一次分隔。Match the pattern of integral and fractional digits separated by a decimal point symbol at least one time.
$ 符合字串的結尾。Match the end of the string.

在此情況下,正則運算式會假設有效的貨幣字串不包含群組分隔符號號,而且沒有任何小數位數或目前文化特性的屬性所定義的小數位數 CurrencyDecimalDigitsIn this case, the regular expression assumes that a valid currency string does not contain group separator symbols, and that it has either no fractional digits or the number of fractional digits defined by the current culture's CurrencyDecimalDigits property.

using System;
using System.Globalization;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      // Get the current NumberFormatInfo object to build the regular 
      // expression pattern dynamically.
      NumberFormatInfo nfi = NumberFormatInfo.CurrentInfo;

      // Define the regular expression pattern.
      string pattern; 
      pattern = @"^\s*[";
      // Get the positive and negative sign symbols.
      pattern += Regex.Escape(nfi.PositiveSign + nfi.NegativeSign) + @"]?\s?";
      // Get the currency symbol.
      pattern += Regex.Escape(nfi.CurrencySymbol) + @"?\s?";
      // Add integral digits to the pattern.
      pattern += @"(\d*";
      // Add the decimal separator.
      pattern += Regex.Escape(nfi.CurrencyDecimalSeparator) + "?";
      // Add the fractional digits.
      pattern += @"\d{";
      // Determine the number of fractional digits in currency values.
      pattern += nfi.CurrencyDecimalDigits.ToString() + "}?){1}$";
      
      Regex rgx = new Regex(pattern);

      // Define some test strings.
      string[] tests = { "-42", "19.99", "0.001", "100 USD", 
                         ".34", "0.34", "1,052.21", "$10.62", 
                         "+1.43", "-$0.23" };

      // Check each test string against the regular expression.
      foreach (string test in tests)
      {
         if (rgx.IsMatch(test))
            Console.WriteLine("{0} is a currency value.", test);
         else
            Console.WriteLine("{0} is not a currency value.", test);
      }
   }
}
// The example displays the following output:
//       -42 is a currency value.
//       19.99 is a currency value.
//       0.001 is not a currency value.
//       100 USD is not a currency value.
//       .34 is a currency value.
//       0.34 is a currency value.
//       1,052.21 is not a currency value.
//       $10.62 is a currency value.
//       +1.43 is a currency value.
//       -$0.23 is a currency value.
Imports System.Globalization
Imports System.Text.RegularExpressions

Public Module Example
   Public Sub Main()
      ' Get the current NumberFormatInfo object to build the regular 
      ' expression pattern dynamically.
      Dim nfi As NumberFormatInfo = NumberFormatInfo.CurrentInfo

      ' Define the regular expression pattern.
      Dim pattern As String 
      pattern = "^\s*["
      ' Get the positive and negative sign symbols.
      pattern += Regex.Escape(nfi.PositiveSign + nfi.NegativeSign) + "]?\s?"
      ' Get the currency symbol.
      pattern += Regex.Escape(nfi.CurrencySymbol) + "?\s?"
      ' Add integral digits to the pattern.
      pattern += "(\d*"
      ' Add the decimal separator.
      pattern += Regex.Escape(nfi.CurrencyDecimalSeparator) + "?"
      ' Add the fractional digits.
      pattern += "\d{"
      ' Determine the number of fractional digits in currency values.
      pattern += nfi.CurrencyDecimalDigits.ToString() + "}?){1}$"
      
      Dim rgx As New Regex(pattern)

      ' Define some test strings.
      Dim tests() As String = {"-42", "19.99", "0.001", "100 USD", _
                               ".34", "0.34", "1,052.21", "$10.62", _
                               "+1.43", "-$0.23" }

      ' Check each test string against the regular expression.
      For Each test As String In tests
         If rgx.IsMatch(test) Then
            Console.WriteLine("{0} is a currency value.", test)
         Else
            Console.WriteLine("{0} is not a currency value.", test)
         End If
      Next
   End Sub
End Module
' The example displays the following output:
'       -42 is a currency value.
'       19.99 is a currency value.
'       0.001 is not a currency value.
'       100 USD is not a currency value.
'       .34 is a currency value.
'       0.34 is a currency value.
'       1,052.21 is not a currency value.
'       $10.62 is a currency value.
'       +1.43 is a currency value.
'       -$0.23 is a currency value.

因為此範例中的正則運算式是動態建立的,所以我們在設計階段並不知道目前文化特性的貨幣符號、小數點正負號或正負號是否可能會被正則運算式引擎誤解為正則運算式語言運算子。Because the regular expression in this example is built dynamically, we do not know at design time whether the current culture's currency symbol, decimal sign, or positive and negative signs might be misinterpreted by the regular expression engine as regular expression language operators. 為了避免任何解釋,此範例會將每個動態產生的字串傳遞給 Escape 方法。To prevent any misinterpretation, the example passes each dynamically generated string to the Escape method.

備註

Regex類別代表 .NET Framework 的正則運算式引擎。The Regex class represents the .NET Framework's regular expression engine. 可以用來快速剖析大量文字,以尋找特定的字元模式;若要解壓縮、編輯、取代或刪除文字子字串;以及將解壓縮的字串加入至集合以產生報表。It can be used to quickly parse large amounts of text to find specific character patterns; to extract, edit, replace, or delete text substrings; and to add the extracted strings to a collection to generate a report.

注意

如果您的主要興趣是藉由判斷字串是否符合特定模式來驗證字串,您可以使用 System.Configuration.RegexStringValidator 類別。If your primary interest is to validate a string by determining whether it conforms to a particular pattern, you can use the System.Configuration.RegexStringValidator class.

若要使用正則運算式,您可以使用 正則運算式語言-快速參考中記載的語法,來定義要在文字資料流程中識別的模式。To use regular expressions, you define the pattern that you want to identify in a text stream by using the syntax documented in Regular Expression Language - Quick Reference. 接下來,您可以選擇性地具現化 Regex 物件。Next, you can optionally instantiate a Regex object. 最後,您會呼叫執行某些作業的方法,例如取代符合正則運算式模式的文字,或識別模式相符專案。Finally, you call a method that performs some operation, such as replacing text that matches the regular expression pattern, or identifying a pattern match.

注意

如需一些常見的正則運算式模式,請參閱 正則運算式範例For some common regular expression patterns, see Regular Expression Examples. 另外還有一些正則運算式模式的線上程式庫,例如 Regular-Expressions.infoThere are also a number of online libraries of regular expression patterns, such as the one at Regular-Expressions.info.

如需使用類別的詳細資訊 Regex ,請參閱本主題中的下列各節:For more information about using the Regex class, see the following sections in this topic:

如需規則運算式語言的詳細資訊,請參閱規則運算式語言 - 快速參考,或下載並列印下列其中一本小手冊:For more information about the regular expression language, see Regular Expression Language - Quick Reference or download and print one of these brochures:

Word (.docx) 格式的快速參考Quick Reference in Word (.docx) format
PDF (.pdf) 格式的快速參考Quick Reference in PDF (.pdf) format

Regex 與字串方法Regex vs. String Methods

System.String類別包含數個搜尋和比較方法,可讓您用來執行與文字的模式比對。The System.String class includes several search and comparison methods that you can use to perform pattern matching with text. 例如, String.ContainsString.EndsWithString.StartsWith 方法會判斷字串實例是否包含指定的子字串,而 String.IndexOfString.IndexOfAny 、和方法會傳回 String.LastIndexOf String.LastIndexOfAny 字串中指定子字串的開始位置。For example, the String.Contains, String.EndsWith, and String.StartsWith methods determine whether a string instance contains a specified substring; and the String.IndexOf, String.IndexOfAny, String.LastIndexOf, and String.LastIndexOfAny methods return the starting position of a specified substring in a string. System.String當您搜尋特定字串時,請使用類別的方法。Use the methods of the System.String class when you are searching for a specific string. Regex當您在字串中搜尋特定模式時,請使用類別。Use the Regex class when you are searching for a specific pattern in a string. 如需詳細資訊和範例,請參閱 .NET Framework 正則運算式For more information and examples, see .NET Framework Regular Expressions.

返回備註Back to Remarks

靜態與實例方法的比較Static vs. Instance Methods

定義正則運算式模式之後,您可以使用下列兩種方式之一,將它提供給正則運算式引擎:After you define a regular expression pattern, you can provide it to the regular expression engine in either of two ways:

  • 藉由具現化 Regex 表示正則運算式的物件。By instantiating a Regex object that represents the regular expression. 若要這樣做,請將正則運算式模式傳遞給函式 RegexTo do this, you pass the regular expression pattern to a Regex constructor. Regex物件是不可變的; 當您 Regex 使用正則運算式具現化物件時,無法變更該物件的正則運算式。A Regex object is immutable; when you instantiate a Regex object with a regular expression, that object's regular expression cannot be changed.

  • 藉由提供正則運算式和文字來搜尋 static Shared Visual Basic) 方法中的 (RegexBy supplying both the regular expression and the text to search to a static (Shared in Visual Basic) Regex method. 這可讓您使用正則運算式,而不需要明確地建立 Regex 物件。This enables you to use a regular expression without explicitly creating a Regex object.

所有 Regex 模式識別方法都包含靜態和實例多載。All Regex pattern identification methods include both static and instance overloads.

正則運算式引擎必須先編譯特定模式,才能使用模式。The regular expression engine must compile a particular pattern before the pattern can be used. 因為 Regex 物件是不可變的,所以這是呼叫類別的函式或靜態方法時所發生的一次性程式 RegexBecause Regex objects are immutable, this is a one-time procedure that occurs when a Regex class constructor or a static method is called. 為了避免重複編譯單一正則運算式的需要,正則運算式引擎會快取靜態方法呼叫中所使用的已編譯正則運算式。To eliminate the need to repeatedly compile a single regular expression, the regular expression engine caches the compiled regular expressions used in static method calls. 因此,正則運算式模式比對方法會針對靜態和實例方法提供類似的效能。As a result, regular expression pattern-matching methods offer comparable performance for static and instance methods.

重要

在 .NET Framework 1.0 和1.1 版中,所有編譯的正則運算式(不論是否使用於實例或靜態方法呼叫中)都會進行快取。In the .NET Framework versions 1.0 and 1.1, all compiled regular expressions, whether they were used in instance or static method calls, were cached. 從 .NET Framework 2.0 開始,只會快取靜態方法呼叫中使用的正則運算式。Starting with the .NET Framework 2.0, only regular expressions used in static method calls are cached.

不過,在下列兩種情況下,快取可能會對效能造成不良的影響:However, caching can adversely affect performance in the following two cases:

  • 當您使用具有大量正則運算式的靜態方法呼叫時。When you use static method calls with a large number of regular expressions. 根據預設,正則運算式引擎會快取15個最近使用的靜態正則運算式。By default, the regular expression engine caches the 15 most recently used static regular expressions. 如果您的應用程式使用超過15個靜態正則運算式,則必須重新編譯某些正則運算式。If your application uses more than 15 static regular expressions, some regular expressions must be recompiled. 若要避免重新編譯,您可以增加 Regex.CacheSize 屬性。To prevent this recompilation, you can increase the Regex.CacheSize property.

  • 當您 Regex 使用先前編譯的正則運算式來具現化新的物件時。When you instantiate new Regex objects with regular expressions that have previously been compiled. 例如,下列程式碼會定義正則運算式,以在文字資料流程中尋找重複的字組。For example, the following code defines a regular expression to locate duplicated words in a text stream. 雖然此範例使用單一正則運算式,但它會將新的物件具現化, Regex 以處理每一行文字。Although the example uses a single regular expression, it instantiates a new Regex object to process each line of text. 這會導致在迴圈的每個反復專案中重新編譯正則運算式。This results in the recompilation of the regular expression with each iteration of the loop.

    StreamReader sr = new StreamReader(filename);
    string input;
    string pattern = @"\b(\w+)\s\1\b";
    while (sr.Peek() >= 0)
    {
       input = sr.ReadLine();
       Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
       MatchCollection matches = rgx.Matches(input);
       if (matches.Count > 0)
       {
          Console.WriteLine("{0} ({1} matches):", input, matches.Count);
          foreach (Match match in matches)
             Console.WriteLine("   " + match.Value);
       }
    }
    sr.Close();   
    
    Dim sr As New StreamReader(filename)
    Dim input As String
    Dim pattern As String = "\b(\w+)\s\1\b"
    Do While sr.Peek() >= 0
       input = sr.ReadLine()
       Dim rgx As New Regex(pattern, RegexOptions.IgnoreCase)
       Dim matches As MatchCollection = rgx.Matches(input)
       If matches.Count > 0 Then
          Console.WriteLine("{0} ({1} matches):", input, matches.Count)
          For Each match As Match In matches
             Console.WriteLine("   " + match.Value)
          Next   
       End If
    Loop
    sr.Close()   
    

    為了避免重新編譯,您應該具現化可供 Regex 所有需要它的程式碼存取的單一物件,如下列重寫範例所示。To prevent recompilation, you should instantiate a single Regex object that is accessible to all code that requires it, as shown in the following rewritten example.

    StreamReader sr = new StreamReader(filename);
    string input;
    string pattern = @"\b(\w+)\s\1\b";
    Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
    
    while (sr.Peek() >= 0)
    {
       input = sr.ReadLine();
       MatchCollection matches = rgx.Matches(input);
       if (matches.Count > 0)
       {
          Console.WriteLine("{0} ({1} matches):", input, matches.Count);
          foreach (Match match in matches)
             Console.WriteLine("   " + match.Value);
       }
    }
    sr.Close();   
    
    Dim sr As New StreamReader(filename)
    Dim input As String
    Dim pattern As String = "\b(\w+)\s\1\b"
    Dim rgx As New Regex(pattern, RegexOptions.IgnoreCase)
    Do While sr.Peek() >= 0
       input = sr.ReadLine()
       Dim matches As MatchCollection = rgx.Matches(input)
       If matches.Count > 0 Then
          Console.WriteLine("{0} ({1} matches):", input, matches.Count)
          For Each match As Match In matches
             Console.WriteLine("   " + match.Value)
          Next   
       End If
    Loop
    sr.Close()   
    

返回備註Back to Remarks

執行正則運算式作業Performing Regular Expression Operations

無論您決定要具現化 Regex 物件,並呼叫其方法或呼叫靜態方法, Regex 類別都會提供下列模式比對功能:Whether you decide to instantiate a Regex object and call its methods or call static methods, the Regex class offers the following pattern-matching functionality:

  • 符合的驗證。Validation of a match. 您可以呼叫 IsMatch 方法來判斷是否有相符的結果。You call the IsMatch method to determine whether a match is present.

  • 單一相符項的抓取。Retrieval of a single match. 您可以呼叫 Match 方法來取出 Match 物件,該物件表示字串中或部分字串中的第一個相符項。You call the Match method to retrieve a Match object that represents the first match in a string or in part of a string. 您可以藉由呼叫方法來抓取後續的相符專案 Match.NextMatchSubsequent matches can be retrieved by calling the Match.NextMatch method.

  • 所有相符專案的抓取。Retrieval of all matches. 您可以呼叫 Matches 方法,以抓取 System.Text.RegularExpressions.MatchCollection 表示在字串或部分字串中找到之所有相符專案的物件。You call the Matches method to retrieve a System.Text.RegularExpressions.MatchCollection object that represents all the matches found in a string or in part of a string.

  • 取代相符的文字。Replacement of matched text. 您可以呼叫 Replace 方法來取代相符的文字。You call the Replace method to replace matched text. 取代文字也可以由正則運算式定義。The replacement text can also be defined by a regular expression. 此外,有些 Replace 方法包含一個 MatchEvaluator 參數,可讓您以程式設計方式定義取代文字。In addition, some of the Replace methods include a MatchEvaluator parameter that enables you to programmatically define the replacement text.

  • 建立從輸入字串的部分形成的字串陣列。Creation of a string array that is formed from parts of an input string. 您可以呼叫 Split 方法,以在正則運算式所定義的位置分割輸入字串。You call the Split method to split an input string at positions that are defined by the regular expression.

除了它的模式比對方法之外,此 Regex 類別還包含數個特殊用途的方法:In addition to its pattern-matching methods, the Regex class includes several special-purpose methods:

  • Escape方法會將任何可能會在正則運算式或輸入字串中解釋為正則運算式運算子的字元進行轉義。The Escape method escapes any characters that may be interpreted as regular expression operators in a regular expression or input string.

  • Unescape方法會移除這些 escape 字元。The Unescape method removes these escape characters.

  • CompileToAssembly方法會建立包含預先定義之正則運算式的元件。The CompileToAssembly method creates an assembly that contains predefined regular expressions. .NET Framework 包含命名空間中這些特殊用途元件的範例 System.Web.RegularExpressionsThe .NET Framework contains examples of these special-purpose assemblies in the System.Web.RegularExpressions namespace.

返回備註Back to Remarks

定義 Time-Out 值Defining a Time-Out Value

.NET Framework 支援功能完整的正則運算式語言,可在模式比對中提供大幅的強大功能和彈性。The .NET Framework supports a full-featured regular expression language that provides substantial power and flexibility in pattern matching. 不過,強大的功能和彈性都有成本:效能不佳的風險。However, the power and flexibility come at a cost: the risk of poor performance. 執行效能不佳的正則運算式很容易建立。Regular expressions that perform poorly are surprisingly easy to create. 在某些情況下,依賴過度回溯的正則運算式作業可能會在處理幾乎符合正則運算式模式的文字時停止回應。In some cases, regular expression operations that rely on excessive backtracking can appear to stop responding when they process text that nearly matches the regular expression pattern. 如需有關 .NET Framework 正則運算式引擎的詳細資訊,請參閱 正則運算式行為的詳細資料For more information about the .NET Framework regular expression engine, see Details of Regular Expression Behavior. 如需過量回溯的詳細資訊,請參閱 回溯For more information about excessive backtracking, see Backtracking.

從開始 .NET Framework 4.5.NET Framework 4.5 ,您可以定義正則運算式相符專案的逾時間隔。Starting with the .NET Framework 4.5.NET Framework 4.5, you can define a time-out interval for regular expression matches. 如果正則運算式引擎無法在此時間間隔內識別相符項,則比對作業會擲回 RegexMatchTimeoutException 例外狀況。If the regular expression engine cannot identify a match within this time interval, the matching operation throws a RegexMatchTimeoutException exception. 在大部分的情況下,這會讓正則運算式引擎不會嘗試比對幾乎符合正則運算式模式的文字,而浪費處理能力。In most cases, this prevents the regular expression engine from wasting processing power by trying to match text that nearly matches the regular expression pattern. 但是,這也可能表示逾時間隔設定過低,或是目前的電腦負載造成整體效能降低。It also could indicate, however, that the timeout interval has been set too low, or that the current machine load has caused an overall degradation in performance.

處理例外狀況的方式取決於例外狀況的原因。How you handle the exception depends on the cause of the exception. 如果發生例外狀況是因為逾時間隔設定過低,或由於電腦負載過高,您可以增加逾時間隔,然後重試比對作業。If the exception occurs because the time-out interval is set too low or because of excessive machine load, you can increase the time-out interval and retry the matching operation. 如果發生例外狀況是因為正則運算式依賴過多回溯,您可以假設符合項不存在,而且您可以選擇性地記錄可協助您修改正則運算式模式的資訊。If the exception occurs because the regular expression relies on excessive backtracking, you can assume that a match does not exist, and, optionally, you can log information that will help you modify the regular expression pattern.

Regex(String, RegexOptions, TimeSpan)當您具現化正則運算式物件時,您可以藉由呼叫函式來設定逾時間隔。You can set a time-out interval by calling the Regex(String, RegexOptions, TimeSpan) constructor when you instantiate a regular expression object. 針對靜態方法,您可以呼叫具有參數之相符方法的多載,以設定逾時間隔 matchTimeoutFor static methods, you can set a time-out interval by calling an overload of a matching method that has a matchTimeout parameter. 如果您未明確設定超時值,預設的超時值會依照下列方式決定:If you do not set a time-out value explicitly, the default time-out value is determined as follows:

  • 使用整個應用程式的超時值(如果有的話)。By using the application-wide time-out value, if one exists. 這可以是任何會套用至應用程式域( Regex 已具現化物件或進行靜態方法呼叫)的超時值。This can be any time-out value that applies to the application domain in which the Regex object is instantiated or the static method call is made. 您可以藉由呼叫 AppDomain.SetData 方法來將值的字串表示指派 TimeSpan 給 "REGEX_DEFAULT_MATCH_TIMEOUT" 屬性,以設定整個應用程式的超時值。You can set the application-wide time-out value by calling the AppDomain.SetData method to assign the string representation of a TimeSpan value to the "REGEX_DEFAULT_MATCH_TIMEOUT" property.

  • InfiniteMatchTimeout如果沒有設定整個應用程式的超時值,則使用值。By using the value InfiniteMatchTimeout, if no application-wide time-out value has been set.

重要

建議您在所有正則運算式模式比對作業中設定超時值。We recommend that you set a time-out value in all regular expression pattern-matching operations. 如需詳細資訊,請參閱 正則運算式的最佳做法For more information, see Best Practices for Regular Expressions.

返回備註Back to Remarks

建構函式

Regex()

初始化 Regex 類別的新執行個體。Initializes a new instance of the Regex class.

Regex(SerializationInfo, StreamingContext)

使用序列化的資料,初始化 Regex 類別的新執行個體。Initializes a new instance of the Regex class by using serialized data.

Regex(String)

為指定的規則運算式初始化 Regex 類別的新執行個體。Initializes a new instance of the Regex class for the specified regular expression.

Regex(String, RegexOptions)

使用會修改模式的選項,為指定的規則運算式初始化 Regex 類別的新執行個體。Initializes a new instance of the Regex class for the specified regular expression, with options that modify the pattern.

Regex(String, RegexOptions, TimeSpan)

針對指定的規則運算式,使用修改模式的選項,以及指定在逾時前模式比對方法應該嘗試比對的時間長度的值,初始化 Regex 類別的新執行個體。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.

欄位

capnames

CompileToAssembly 方法所產生的 Regex 物件使用。Used by a Regex object generated by the CompileToAssembly method.

caps

CompileToAssembly 方法所產生的 Regex 物件使用。Used by a Regex object generated by the CompileToAssembly method.

capsize

CompileToAssembly 方法所產生的 Regex 物件使用。Used by a Regex object generated by the CompileToAssembly method.

capslist

CompileToAssembly 方法所產生的 Regex 物件使用。Used by a Regex object generated by the CompileToAssembly method.

factory

CompileToAssembly 方法所產生的 Regex 物件使用。Used by a Regex object generated by the CompileToAssembly method.

InfiniteMatchTimeout

指定模式比對作業不應逾時。Specifies that a pattern-matching operation should not time out.

internalMatchTimeout

在作業逾時之前可在模式比對作業中流逝的最長時間。The maximum amount of time that can elapse in a pattern-matching operation before the operation times out.

pattern

CompileToAssembly 方法所產生的 Regex 物件使用。Used by a Regex object generated by the CompileToAssembly method.

roptions

CompileToAssembly 方法所產生的 Regex 物件使用。Used by a Regex object generated by the CompileToAssembly method.

屬性

CacheSize

取得或設定在已編譯規則運算式目前靜態快取中項目的最大數目。Gets or sets the maximum number of entries in the current static cache of compiled regular expressions.

CapNames

取得或設定字典,對應具名擷取群組及其索引值。Gets or sets a dictionary that maps named capturing groups to their index values.

Caps

取得或設定字典,對應編號的擷取群組及其索引值。Gets or sets a dictionary that maps numbered capturing groups to their index values.

MatchTimeout

取得目前執行個體的逾時間隔。Gets the time-out interval of the current instance.

Options

取得傳入 Regex 建構函式的選項。Gets the options that were passed into the Regex constructor.

RightToLeft

取得值,指出規則運算式是否由右至左搜尋。Gets a value that indicates whether the regular expression searches from right to left.

方法

CompileToAssembly(RegexCompilationInfo[], AssemblyName)

將一個或多個指定的 Regex 物件編譯為具名組件。Compiles one or more specified Regex objects to a named assembly.

CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[])

將一個或多個指定的 Regex 物件編譯為具有指定之屬性的具名組件。Compiles one or more specified Regex objects to a named assembly with the specified attributes.

CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[], String)

將一個或多個指定的 Regex 物件和指定的資源檔編譯為具有指定之屬性的具名組件。Compiles one or more specified Regex objects and a specified resource file to a named assembly with the specified attributes.

Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(繼承來源 Object)
Escape(String)

以逸出程式碼取代字元 (\、*、+、?、|、{、[、(、)、^、$、.、# 和空白字元) 的最小集合,以便逸出這些字元。Escapes a minimal set of characters (\, *, +, ?, |, {, [, (,), ^, $, ., #, and white space) by replacing them with their escape codes. 這樣會指示規則運算式引擎將這些字元解譯為常值,而非解譯為中繼字元。This instructs the regular expression engine to interpret these characters literally rather than as metacharacters.

Finalize()

這個成員會覆寫 Finalize(),您可以在該主題中找到更完整的文件。This member overrides Finalize(), and more complete documentation might be available in that topic.

在記憶體回收 (GC) 回收 Object 前,允許 Object 嘗試釋放資源並執行其他清除作業。Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection.

GetGroupNames()

傳回規則運算式的擷取群組名稱的陣列。Returns an array of capturing group names for the regular expression.

GetGroupNumbers()

傳回對應陣列中群組名稱的擷取群組編號的陣列。Returns an array of capturing group numbers that correspond to group names in an array.

GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(繼承來源 Object)
GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(繼承來源 Object)
GroupNameFromNumber(Int32)

取得對應指定群組編號的群組名稱。Gets the group name that corresponds to the specified group number.

GroupNumberFromName(String)

傳回對應指定群組名稱的群組編號。Returns the group number that corresponds to the specified group name.

InitializeReferences()

CompileToAssembly 方法所產生的 Regex 物件使用。Used by a Regex object generated by the CompileToAssembly method.

IsMatch(String)

表示 Regex 建構函式中指定的規則運算式是否要在指定的輸入字串中尋找相符項目。Indicates whether the regular expression specified in the Regex constructor finds a match in a specified input string.

IsMatch(String, Int32)

表示 Regex 建構函式中所指定的規則運算式,是否要從字串中指定的起始位置開始,在指定的輸入字串中尋找相符項目。Indicates whether the regular expression specified in the Regex constructor finds a match in the specified input string, beginning at the specified starting position in the string.

IsMatch(String, String)

表示指定的規則運算式是否在指定的輸入字串中尋找相符項目。Indicates whether the specified regular expression finds a match in the specified input string.

IsMatch(String, String, RegexOptions)

表示指定的規則運算式是否使用指定的比對選項,在指定的輸入字串中尋找相符項目。Indicates whether the specified regular expression finds a match in the specified input string, using the specified matching options.

IsMatch(String, String, RegexOptions, TimeSpan)

指出指定的規則運算式是否使用指定的比對選項和逾時間隔,在指定的輸入字串中尋找相符項目。Indicates whether the specified regular expression finds a match in the specified input string, using the specified matching options and time-out interval.

Match(String)

在指定的輸入字串中,搜尋符合 Regex 建構函式中所指定規則運算式的第一個項目。Searches the specified input string for the first occurrence of the regular expression specified in the Regex constructor.

Match(String, Int32)

從字串中指定的開始位置開始,在輸入字串中搜尋規則運算式的第一個相符項目。Searches the input string for the first occurrence of a regular expression, beginning at the specified starting position in the string.

Match(String, Int32, Int32)

從指定的開始位置開始並且僅搜尋指定數目的字元,在輸入字串中搜尋規則運算式的第一個相符項目。Searches the input string for the first occurrence of a regular expression, beginning at the specified starting position and searching only the specified number of characters.

Match(String, String)

在指定的輸入字串中搜尋所指定規則運算式的第一個相符項目。Searches the specified input string for the first occurrence of the specified regular expression.

Match(String, String, RegexOptions)

使用指定的比對選項,在輸入字串中搜尋所指定規則運算式的第一個相符項目。Searches the input string for the first occurrence of the specified regular expression, using the specified matching options.

Match(String, String, RegexOptions, TimeSpan)

使用指定的比對選項和逾時間隔,在輸入字串中搜尋所指定規則運算式的第一個相符項目。Searches the input string for the first occurrence of the specified regular expression, using the specified matching options and time-out interval.

Matches(String)

在指定的輸入字串搜尋規則運算式的所有項目。Searches the specified input string for all occurrences of a regular expression.

Matches(String, Int32)

自字串中指定的開始位置開始,在指定的輸入字串搜尋規則運算式的所有項目。Searches the specified input string for all occurrences of a regular expression, beginning at the specified starting position in the string.

Matches(String, String)

在指定的輸入字串搜尋所指定規則運算式的所有相符項目。Searches the specified input string for all occurrences of a specified regular expression.

Matches(String, String, RegexOptions)

使用指定的比對選項在指定的輸入字串中,搜尋所指定規則運算式的所有相符項目。Searches the specified input string for all occurrences of a specified regular expression, using the specified matching options.

Matches(String, String, RegexOptions, TimeSpan)

使用指定的比對選項和逾時間隔,在指定的輸入字串中搜尋所指定規則運算式的所有相符項目。Searches the specified input string for all occurrences of a specified regular expression, using the specified matching options and time-out interval.

MemberwiseClone()

建立目前 Object 的淺層複製。Creates a shallow copy of the current Object.

(繼承來源 Object)
Replace(String, MatchEvaluator)

在指定的輸入字串中,使用由 MatchEvaluator 委派所傳回的字串,取代所有與指定之規則運算式相符的字串。In a specified input string, replaces all strings that match a specified regular expression with a string returned by a MatchEvaluator delegate.

Replace(String, MatchEvaluator, Int32)

在指定的輸入字串中,使用 MatchEvaluator 委派所傳回的字串來取代符合規則運算式模式的指定最大字串數目。In a specified input string, replaces a specified maximum number of strings that match a regular expression pattern with a string returned by a MatchEvaluator delegate.

Replace(String, MatchEvaluator, Int32, Int32)

在指定的輸入子字串中,使用 MatchEvaluator 委派所傳回的字串來取代符合規則運算式模式的指定最大字串數目。In a specified input substring, replaces a specified maximum number of strings that match a regular expression pattern with a string returned by a MatchEvaluator delegate.

Replace(String, String)

在指定的輸入字串中,使用指定的取代字串來取代符合規則運算式模式的所有字串。In a specified input string, replaces all strings that match a regular expression pattern with a specified replacement string.

Replace(String, String, Int32)

在指定的輸入字串中,使用指定的取代字串來取代符合規則運算式模式的指定最大字串數目。In a specified input string, replaces a specified maximum number of strings that match a regular expression pattern with a specified replacement string.

Replace(String, String, Int32, Int32)

在指定的輸入子字串中,使用指定的取代字串來取代符合規則運算式模式的指定最大字串數目。In a specified input substring, replaces a specified maximum number of strings that match a regular expression pattern with a specified replacement string.

Replace(String, String, MatchEvaluator)

在指定的輸入字串中,使用由 MatchEvaluator 委派所傳回的字串,取代所有與指定之規則運算式相符的字串。In a specified input string, replaces all strings that match a specified regular expression with a string returned by a MatchEvaluator delegate.

Replace(String, String, MatchEvaluator, RegexOptions)

在指定的輸入字串中,使用由 MatchEvaluator 委派所傳回的字串,取代所有與指定之規則運算式相符的字串。In a specified input string, replaces all strings that match a specified regular expression with a string returned by a MatchEvaluator delegate. 指定的選項會修改符合的作業。Specified options modify the matching operation.

Replace(String, String, MatchEvaluator, RegexOptions, TimeSpan)

在指定的輸入字串中,使用 MatchEvaluator 委派所傳回的字串,取代所有與指定之規則運算式相符的子字串。In a specified input string, replaces all substrings that match a specified regular expression with a string returned by a MatchEvaluator delegate. 如果沒有找到相符項目,其他參數會指定修改比對作業的選項和逾時間隔。Additional parameters specify options that modify the matching operation and a time-out interval if no match is found.

Replace(String, String, String)

在指定的輸入字串中,使用指定的取代字串來取代符合指定之規則運算式的所有字串。In a specified input string, replaces all strings that match a specified regular expression with a specified replacement string.

Replace(String, String, String, RegexOptions)

在指定的輸入字串中,使用指定的取代字串來取代符合指定之規則運算式的所有字串。In a specified input string, replaces all strings that match a specified regular expression with a specified replacement string. 指定的選項會修改符合的作業。Specified options modify the matching operation.

Replace(String, String, String, RegexOptions, TimeSpan)

在指定的輸入字串中,使用指定的取代字串來取代符合指定之規則運算式的所有字串。In a specified input string, replaces all strings that match a specified regular expression with a specified replacement string. 如果沒有找到相符項目,其他參數會指定修改比對作業的選項和逾時間隔。Additional parameters specify options that modify the matching operation and a time-out interval if no match is found.

Split(String)

Regex 建構函式中指定之規則運算式模式所定義的位置,將輸入字串分隔成子字串的陣列。Splits an input string into an array of substrings at the positions defined by a regular expression pattern specified in the Regex constructor.

Split(String, Int32)

Regex 建構函式中指定的規則運算式所定義的位置,以指定的最大次數來將輸入字串分隔成子字串的陣列。Splits an input string a specified maximum number of times into an array of substrings, at the positions defined by a regular expression specified in the Regex constructor.

Split(String, Int32, Int32)

Regex 建構函式中指定的規則運算式所定義的位置,以指定的最大次數來將輸入字串分隔成子字串的陣列。Splits an input string a specified maximum number of times into an array of substrings, at the positions defined by a regular expression specified in the Regex constructor. 規則運算式模式從輸入字串中指定的字元位置開始搜尋。The search for the regular expression pattern starts at a specified character position in the input string.

Split(String, String)

在規則運算式模式所定義的位置,將輸入字串分割成子字串陣列。Splits an input string into an array of substrings at the positions defined by a regular expression pattern.

Split(String, String, RegexOptions)

在指定的規則運算式模式所定義的位置,將輸入字串分割成子字串陣列。Splits an input string into an array of substrings at the positions defined by a specified regular expression pattern. 指定的選項會修改符合的作業。Specified options modify the matching operation.

Split(String, String, RegexOptions, TimeSpan)

在指定的規則運算式模式所定義的位置,將輸入字串分割成子字串陣列。Splits an input string into an array of substrings at the positions defined by a specified regular expression pattern. 如果沒有找到相符項目,其他參數會指定修改比對作業的選項和逾時間隔。Additional parameters specify options that modify the matching operation and a time-out interval if no match is found.

ToString()

傳回傳遞至 Regex 建構函式中的規則運算式模式。Returns the regular expression pattern that was passed into the Regex constructor.

Unescape(String)

轉換輸入字串中任何逸出的字元。Converts any escaped characters in the input string.

UseOptionC()

CompileToAssembly 方法所產生的 Regex 物件使用。Used by a Regex object generated by the CompileToAssembly method.

UseOptionR()

CompileToAssembly 方法所產生的 Regex 物件使用。Used by a Regex object generated by the CompileToAssembly method.

ValidateMatchTimeout(TimeSpan)

檢查逾時間隔是否在可接受的範圍內。Checks whether a time-out interval is within an acceptable range.

明確介面實作

ISerializable.GetObjectData(SerializationInfo, StreamingContext)

將還原序列化目前 SerializationInfo 物件所需的資料填入 (Populate) Regex 物件。Populates a SerializationInfo object with the data necessary to deserialize the current Regex object.

適用於

執行緒安全性

Regex類別是不可變的 (唯讀) 和安全線程。The Regex class is immutable (read-only) and thread safe. Regex 可以在任何執行緒上建立物件,並線上程之間共用。Regex objects can be created on any thread and shared between threads. 如需詳細資訊,請參閱 執行緒安全性For more information, see Thread Safety.

另請參閱