Regex Regex Regex Regex Class

定義

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

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

範例

下列範例會使用規則運算式,檢查有重複出現的文字字串中。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
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.CurrencyDecimalSeparatorCurrencyDecimalDigitsNumberFormatInfo.CurrencySymbolNumberFormatInfo.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.

在此情況下,規則運算式假設有效貨幣字串不包含群組分隔符號,而且它有沒有小數位數或目前的文化特性所定義的小數位數數目CurrencyDecimalDigits屬性。In 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. 另外還有幾個的線上程式庫的規則運算式模式,例如在一般 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 vs。字串方法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.EndsWith,和String.StartsWith判斷方法的字串執行個體是否包含指定的子字串; 和String.IndexOfString.IndexOfAnyString.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. 若要這樣做,您會傳遞至規則運算式模式Regex建構函式。To do this, you pass the regular expression pattern to a Regex constructor. ARegex物件是不可變,當您具現化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 中)Regex方法。By 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物件是不可變,這樣一來,就會發生的一次性程序時Regex呼叫類別建構函式或靜態方法。Because 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.NextMatch方法。Subsequent 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方法會移除這些逸出字元。The Unescape method removes these escape characters.

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

回到 < 備註 >Back to Remarks

定義的逾時值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. 對於靜態方法,您可以設定逾時間隔,藉由呼叫的比對方法的多載matchTimeout參數。For 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() Regex() Regex()

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

Regex(SerializationInfo, StreamingContext) Regex(SerializationInfo, StreamingContext) Regex(SerializationInfo, StreamingContext) Regex(SerializationInfo, StreamingContext)

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

Regex(String) Regex(String) Regex(String) Regex(String)

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

Regex(String, RegexOptions) Regex(String, RegexOptions) Regex(String, RegexOptions) 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(String, RegexOptions, TimeSpan) Regex(String, RegexOptions, TimeSpan) 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 capnames capnames capnames

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

caps caps caps caps

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

capsize capsize capsize capsize

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

capslist capslist capslist capslist

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

factory factory factory factory

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

InfiniteMatchTimeout InfiniteMatchTimeout InfiniteMatchTimeout InfiniteMatchTimeout

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

internalMatchTimeout internalMatchTimeout internalMatchTimeout internalMatchTimeout

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

pattern pattern pattern pattern

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

roptions roptions roptions roptions

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

屬性

CacheSize CacheSize CacheSize CacheSize

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

CapNames CapNames CapNames CapNames

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

Caps Caps Caps Caps

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

MatchTimeout MatchTimeout MatchTimeout MatchTimeout

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

Options Options Options Options

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

RightToLeft RightToLeft RightToLeft RightToLeft

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

方法

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

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

CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[]) CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[]) CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[]) 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) CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[], String) CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[], String) 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) Equals(Object) Equals(Object) Equals(Object)

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

(Inherited from Object)
Escape(String) Escape(String) Escape(String) 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() Finalize() Finalize()

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

可讓Object嘗試釋放資源並執行其他清除作業後的Object記憶體回收 (gc) 回收。Allows an Object to attempt to free resources and perform other cleanup operations before the Object is reclaimed by garbage collection.

GetGroupNames() GetGroupNames() GetGroupNames() GetGroupNames()

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

GetGroupNumbers() GetGroupNumbers() GetGroupNumbers() GetGroupNumbers()

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

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

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

(Inherited from Object)
GetType() GetType() GetType() GetType()

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

(Inherited from Object)
GroupNameFromNumber(Int32) GroupNameFromNumber(Int32) GroupNameFromNumber(Int32) GroupNameFromNumber(Int32)

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

GroupNumberFromName(String) GroupNumberFromName(String) GroupNumberFromName(String) GroupNumberFromName(String)

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

InitializeReferences() InitializeReferences() InitializeReferences() InitializeReferences()

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

IsMatch(String) IsMatch(String) IsMatch(String) IsMatch(String)

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

IsMatch(String, Int32) IsMatch(String, Int32) IsMatch(String, Int32) 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) IsMatch(String, String) IsMatch(String, String) IsMatch(String, String)

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

IsMatch(String, String, RegexOptions) IsMatch(String, String, RegexOptions) IsMatch(String, String, RegexOptions) 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) IsMatch(String, String, RegexOptions, TimeSpan) IsMatch(String, String, RegexOptions, TimeSpan) 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) Match(String) Match(String) Match(String)

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

Match(String, Int32) Match(String, Int32) Match(String, Int32) 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) Match(String, Int32, Int32) Match(String, Int32, Int32) 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) Match(String, String) Match(String, String) Match(String, String)

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

Match(String, String, RegexOptions) Match(String, String, RegexOptions) Match(String, String, RegexOptions) 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) Match(String, String, RegexOptions, TimeSpan) Match(String, String, RegexOptions, TimeSpan) 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) Matches(String) Matches(String) Matches(String)

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

Matches(String, Int32) Matches(String, Int32) Matches(String, Int32) 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) Matches(String, String) Matches(String, String) Matches(String, String)

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

Matches(String, String, RegexOptions) Matches(String, String, RegexOptions) Matches(String, String, RegexOptions) 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) Matches(String, String, RegexOptions, TimeSpan) Matches(String, String, RegexOptions, TimeSpan) 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() MemberwiseClone() MemberwiseClone() MemberwiseClone()

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

(Inherited from Object)
Replace(String, MatchEvaluator) Replace(String, MatchEvaluator) Replace(String, MatchEvaluator) 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) Replace(String, MatchEvaluator, Int32) Replace(String, MatchEvaluator, Int32) 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) Replace(String, MatchEvaluator, Int32, Int32) Replace(String, MatchEvaluator, Int32, Int32) 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) Replace(String, String) Replace(String, String) 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) Replace(String, String, Int32) Replace(String, String, Int32) 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) Replace(String, String, Int32, Int32) Replace(String, String, Int32, Int32) 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) Replace(String, String, MatchEvaluator) Replace(String, String, MatchEvaluator) 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) Replace(String, String, MatchEvaluator, RegexOptions) Replace(String, String, MatchEvaluator, RegexOptions) 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) Replace(String, String, MatchEvaluator, RegexOptions, TimeSpan) Replace(String, String, MatchEvaluator, RegexOptions, TimeSpan) 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) Replace(String, String, String) Replace(String, String, String) 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) Replace(String, String, String, RegexOptions) Replace(String, String, String, RegexOptions) 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) Replace(String, String, String, RegexOptions, TimeSpan) Replace(String, String, String, RegexOptions, TimeSpan) 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) Split(String) Split(String) 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) Split(String, Int32) Split(String, Int32) 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) Split(String, Int32, Int32) Split(String, Int32, Int32) 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) Split(String, String) Split(String, 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) Split(String, String, RegexOptions) Split(String, String, RegexOptions) 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) Split(String, String, RegexOptions, TimeSpan) Split(String, String, RegexOptions, TimeSpan) 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() ToString() ToString() ToString()

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

Unescape(String) Unescape(String) Unescape(String) Unescape(String)

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

UseOptionC() UseOptionC() UseOptionC() UseOptionC()

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

UseOptionR() UseOptionR() UseOptionR() UseOptionR()

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

ValidateMatchTimeout(TimeSpan) ValidateMatchTimeout(TimeSpan) ValidateMatchTimeout(TimeSpan) ValidateMatchTimeout(TimeSpan)

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

明確介面實作

ISerializable.GetObjectData(SerializationInfo, StreamingContext) ISerializable.GetObjectData(SerializationInfo, StreamingContext) ISerializable.GetObjectData(SerializationInfo, StreamingContext) 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. 如需詳細資訊,請參閱 <<c0> 的執行緒安全For more information, see Thread Safety.

另請參閱