Regex.Matches Regex.Matches Regex.Matches Regex.Matches Method

定義

在輸入字串中搜尋規則運算式的所有項目,並傳回所有符合項目。Searches an input string for all occurrences of a regular expression and returns all the matches.

多載

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.

Matches(String) Matches(String) Matches(String) Matches(String)

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

public:
 System::Text::RegularExpressions::MatchCollection ^ Matches(System::String ^ input);
public System.Text.RegularExpressions.MatchCollection Matches (string input);
member this.Matches : string -> System.Text.RegularExpressions.MatchCollection
Public Function Matches (input As String) As MatchCollection

參數

input
String String String String

用來搜尋比對的字串。The string to search for a match.

傳回

搜尋之後找到的 Match 物件集合。A collection of the Match objects found by the search. 如果找不到相符的項目,此方法會傳回空集合物件。If no matches are found, the method returns an empty collection object.

例外狀況

範例

下列範例會使用Matches(String)方法來識別句子結尾為 "es" 的任何字組。The following example uses the Matches(String) method to identify any words in a sentence that end in "es".

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"\b\w+es\b";
      Regex rgx = new Regex(pattern);
      string sentence = "Who writes these notes?";
      
      foreach (Match match in rgx.Matches(sentence))
         Console.WriteLine("Found '{0}' at position {1}", 
                           match.Value, match.Index);
   }
}
// The example displays the following output:
//       Found 'writes' at position 4
//       Found 'notes' at position 17
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim pattern As String = "\b\w+es\b"
      Dim rgx As New Regex(pattern)
      Dim sentence As String = "Who writes these notes?"
      
      For Each match As Match In rgx.Matches(sentence)
         Console.WriteLine("Found '{0}' at position {1}", match.Value, match.Index)
      Next
   End Sub
End Module
' The example displays the following output:
'       Found 'writes' at position 4
'       Found 'notes' at position 17

規則運算式模式 \b\w+es\b 的定義如下表所示。The regular expression pattern \b\w+es\b is defined as shown in the following table.

模式Pattern 說明Description
\b 開始字緣比對。Begin the match at a word boundary.
\w+ 比對一個或多個文字字元。Match one or more word characters.
es 符合常值字串 "es"。Match the literal string "es".
\b 結束字緣比對。End the match at a word boundary.

備註

方法與Match(String)方法類似, 不同之處在于它會傳回在輸入字串中找到之所有相符專案的相關資訊, 而不是單一相符專案。 Matches(String)The Matches(String) method is similar to the Match(String) method, except that it returns information about all the matches found in the input string, instead of a single match. 它相當於下列程式碼:It is equivalent to the following code:

Match match = regex.Match(input);
while (match.Success) {
      // Handle match here...

      match = match.NextMatch();
}  
Dim match As Match = regex.Match(input)
Do While match.Success
      ' Handle match here...

      match = match.NextMatch()
Loop  

集合只包含符合專案, 並在第一個不相符時終止。The collection includes only matches and terminates at the first non-match.

Matches(String)方法搜尋的正則運算式模式是由呼叫其中一個Regex類別的函式所定義。The regular expression pattern for which the Matches(String) method searches is defined by the call to one of the Regex class constructors. 如需可形成正則運算式模式之元素的詳細資訊, 請參閱正則運算式語言-快速參考For more information about the elements that can form a regular expression pattern, see Regular Expression Language - Quick Reference.

方法會使用「延遲評估」來填入MatchCollection傳回的物件。 MatchesThe Matches method uses lazy evaluation to populate the returned MatchCollection object. 存取這個集合的成員 (例如 MatchCollection.CountMatchCollection.CopyTo) 會導致立即填入集合。Accessing members of this collection such as MatchCollection.Count and MatchCollection.CopyTo causes the collection to be populated immediately. 若要利用延遲評估, 您應該使用結構 (例如和foreach C# For Each中的) 來逐一查看集合 .。NextTo take advantage of lazy evaluation, you should iterate the collection by using a construct such as foreach in C# and For EachNext 在 Visual Basic 中。in Visual Basic.

因為它的延遲評估, 所以呼叫Matches(String)方法並不會RegexMatchTimeoutException擲回例外狀況。Because of its lazy evaluation, calling the Matches(String) method does not throw a RegexMatchTimeoutException exception. 不過, MatchCollection MatchTimeout如果屬性不Regex.InfiniteMatchTimeout是, 而且比對作業超過逾時間隔, 則會在此方法所傳回的物件上執行作業時, 就會擲回例外狀況。However, the exception is thrown when an operation is performed on the MatchCollection object returned by this method, if the MatchTimeout property is not Regex.InfiniteMatchTimeout and a matching operation exceeds the time-out interval.

另請參閱

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.

public:
 System::Text::RegularExpressions::MatchCollection ^ Matches(System::String ^ input, int startat);
public System.Text.RegularExpressions.MatchCollection Matches (string input, int startat);
member this.Matches : string * int -> System.Text.RegularExpressions.MatchCollection
Public Function Matches (input As String, startat As Integer) As MatchCollection

參數

input
String String String String

用來搜尋比對的字串。The string to search for a match.

startat
Int32 Int32 Int32 Int32

在輸入字串中開始搜尋的字元位置。The character position in the input string at which to start the search.

傳回

搜尋之後找到的 Match 物件集合。A collection of the Match objects found by the search. 如果找不到相符的項目,此方法會傳回空集合物件。If no matches are found, the method returns an empty collection object.

例外狀況

startat 小於零或大於 input 的長度。startat is less than zero or greater than the length of input.

範例

下列範例會使用Match(String)方法來尋找以 "es" 結尾的句子中的第一個單字, 然後Matches(String, Int32)呼叫方法來識別任何以 "es" 結尾的其他字。The following example uses the Match(String) method to find the first word in a sentence that ends in "es", and then calls the Matches(String, Int32) method to identify any additional words that end in "es".

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"\b\w+es\b";
      Regex rgx = new Regex(pattern);
      string sentence = "Who writes these notes and uses our paper?";
      
      // Get the first match.
      Match match = rgx.Match(sentence);
      if (match.Success) {
         Console.WriteLine("Found first 'es' in '{0}' at position {1}", 
                           match.Value, match.Index);
         // Get any additional matches.
         foreach (Match m in rgx.Matches(sentence, match.Index + match.Length))
            Console.WriteLine("Also found '{0}' at position {1}", 
                              m.Value, m.Index);
      }   
   }
}
// The example displays the following output:
//       Found first 'es' in 'writes' at position 4
//       Also found 'notes' at position 17
//       Also found 'uses' at position 27
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim pattern As String = "\b\w+es\b"
      Dim rgx As New Regex(pattern)
      Dim sentence As String = "Who writes these notes and uses our paper?"
      
      ' Get the first match.
      Dim match As Match = rgx.Match(sentence)
      If match.Success Then
         Console.WriteLine("Found first 'es' in '{0}' at position {1}", _
                           match.Value, match.Index)
         ' Get any additional matches.
         For Each match In rgx.Matches(sentence, match.Index + match.Length)
            Console.WriteLine("Also found '{0}' at position {1}", _
                              match.Value, match.Index)
         Next
      End If   
   End Sub
End Module
' The example displays the following output:
'       Found first 'es' in 'writes' at position 4
'       Also found 'notes' at position 17
'       Also found 'uses' at position 27

規則運算式模式 \b\w+es\b 的定義如下表所示。The regular expression pattern \b\w+es\b is defined as shown in the following table.

模式Pattern 說明Description
\b 開始字緣比對。Begin the match at a word boundary.
\w+ 比對一個或多個文字字元。Match one or more word characters.
es 符合常值字串 "es"。Match the literal string "es".
\b 結束字緣比對。End the match at a word boundary.

備註

方法與Match(String, Int32)方法類似, 不同之處在于它會傳回在輸入字串中找到之所有相符專案的相關資訊, 而不是單一相符專案。 Matches(String, Int32)The Matches(String, Int32) method is similar to the Match(String, Int32) method, except that it returns information about all the matches found in the input string, instead of a single match. 它相當於下列程式碼:It is equivalent to the following code:

Match match = regex.Match(input, startAt);
while (match.Success) {
      // Handle match here...

      match = match.NextMatch();
}  
Dim match As Match = regex.Match(input, startAt)
Do While match.Success
      ' Handle match here...

      match = match.NextMatch()
Loop  

Matches(String, Int32)方法搜尋的正則運算式模式是由呼叫其中一個Regex類別的函式所定義。The regular expression pattern for which the Matches(String, Int32) method searches is defined by the call to one of the Regex class constructors. 如需可形成正則運算式模式之元素的詳細資訊, 請參閱正則運算式語言-快速參考For more information about the elements that can form a regular expression pattern, see Regular Expression Language - Quick Reference.

方法會使用「延遲評估」來填入MatchCollection傳回的物件。 MatchesThe Matches method uses lazy evaluation to populate the returned MatchCollection object. 存取這個集合的成員 (例如 MatchCollection.CountMatchCollection.CopyTo) 會導致立即填入集合。Accessing members of this collection such as MatchCollection.Count and MatchCollection.CopyTo causes the collection to be populated immediately. 若要利用延遲評估, 您應該使用結構 (例如和foreach C# For Each中的) 來逐一查看集合 .。NextTo take advantage of lazy evaluation, you should iterate the collection by using a construct such as foreach in C# and For EachNext 在 Visual Basic 中。in Visual Basic.

因為它的延遲評估, 所以呼叫Matches(String, Int32)方法並不會RegexMatchTimeoutException擲回例外狀況。Because of its lazy evaluation, calling the Matches(String, Int32) method does not throw a RegexMatchTimeoutException exception. 不過, MatchCollection MatchTimeout如果屬性不Regex.InfiniteMatchTimeout是, 而且比對作業超過逾時間隔, 則會在此方法所傳回的物件上執行作業時, 就會擲回例外狀況。However, the exception is thrown when an operation is performed on the MatchCollection object returned by this method, if the MatchTimeout property is not Regex.InfiniteMatchTimeout and a matching operation exceeds the time-out interval.

另請參閱

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.

public:
 static System::Text::RegularExpressions::MatchCollection ^ Matches(System::String ^ input, System::String ^ pattern);
public static System.Text.RegularExpressions.MatchCollection Matches (string input, string pattern);
static member Matches : string * string -> System.Text.RegularExpressions.MatchCollection
Public Shared Function Matches (input As String, pattern As String) As MatchCollection

參數

input
String String String String

用來搜尋比對的字串。The string to search for a match.

pattern
String String String String

要比對的規則運算式模式。The regular expression pattern to match.

傳回

搜尋之後找到的 Match 物件集合。A collection of the Match objects found by the search. 如果找不到相符的項目,此方法會傳回空集合物件。If no matches are found, the method returns an empty collection object.

例外狀況

發生規則運算式剖析錯誤。A regular expression parsing error occurred.

inputpatternnullinput or pattern is null.

範例

下列範例會使用Matches(String, String)方法來識別句子結尾為 "es" 的任何單字。The following example uses the Matches(String, String) method to identify any word in a sentence that ends in "es".

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"\b\w+es\b";
      string sentence = "Who writes these notes?";
      
      foreach (Match match in Regex.Matches(sentence, pattern))
         Console.WriteLine("Found '{0}' at position {1}", 
                           match.Value, match.Index);
   }
}
// The example displays the following output:
//       Found 'writes' at position 4
//       Found 'notes' at position 17
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim pattern As String = "\b\w+es\b"
      Dim sentence As String = "Who writes these notes?"
      For Each match As Match In Regex.Matches(sentence, pattern)
         Console.WriteLine("Found '{0}' at position {1}", match.Value, match.Index)
      Next
   End Sub
End Module
' The example displays the following output:
'       Found 'writes' at position 4
'       Found 'notes' at position 17

規則運算式模式 \b\w+es\b 的定義如下表所示。The regular expression pattern \b\w+es\b is defined as shown in the following table.

模式Pattern 說明Description
\b 開始字緣比對。Begin the match at a word boundary.
\w+ 比對一個或多個文字字元。Match one or more word characters.
es 符合常值字串 "es"。Match the literal string "es".
\b 結束字緣比對。End the match at a word boundary.

備註

方法與Match(String, String)方法類似, 不同之處在于它會傳回在輸入字串中找到之所有相符專案的相關資訊, 而不是單一相符專案。 Matches(String, String)The Matches(String, String) method is similar to the Match(String, String) method, except that it returns information about all the matches found in the input string, instead of a single match. 它相當於下列程式碼:It is equivalent to the following code:

Match match = Regex.Match(input, pattern);
while (match.Success) {
      // Handle match here...

      match = match.NextMatch();
}  
Dim match As Match = Regex.Match(input, pattern)
Do While match.Success
      ' Handle match here...

      match = match.NextMatch()
Loop  

靜態Matches方法相當於使用指定的正Regex則運算式模式來建立物件, 並呼叫實例方法MatchesThe static Matches methods are equivalent to constructing a Regex object with the specified regular expression pattern and calling the instance method Matches.

pattern 參數包含規則運算式語言項目,以透過符號描述要比對的字串。The pattern parameter consists of regular expression language elements that symbolically describe the string to match. 如需正則運算式的詳細資訊, 請參閱.NET Framework 正則運算式正則運算式語言-快速參考For more information about regular expressions, see .NET Framework Regular Expressions and Regular Expression Language - Quick Reference.

方法會使用「延遲評估」來填入MatchCollection傳回的物件。 MatchesThe Matches method uses lazy evaluation to populate the returned MatchCollection object. 存取這個集合的成員 (例如 MatchCollection.CountMatchCollection.CopyTo) 會導致立即填入集合。Accessing members of this collection such as MatchCollection.Count and MatchCollection.CopyTo causes the collection to be populated immediately. 若要利用延遲評估, 您應該使用結構 (例如和foreach C# For Each中的) 來逐一查看集合 .。NextTo take advantage of lazy evaluation, you should iterate the collection by using a construct such as foreach in C# and For EachNext 在 Visual Basic 中。in Visual Basic.

因為它的延遲評估, 所以呼叫Matches(String, String)方法並不會RegexMatchTimeoutException擲回例外狀況。Because of its lazy evaluation, calling the Matches(String, String) method does not throw a RegexMatchTimeoutException exception. 不過, 在此方法所傳回的MatchCollection物件上執行作業時, 如果逾時間隔是由目前應用程式域的 "REGEX_DEFAULT_MATCH_TIMEOUT" 屬性和比對作業所定義, 就會擲回例外狀況。超過此逾時間隔。However, the exception is thrown when an operation is performed on the MatchCollection object returned by this method, if a time-out interval is defined by the "REGEX_DEFAULT_MATCH_TIMEOUT" property of the current application domain and a matching operation exceeds this time-out interval.

給呼叫者的注意事項

這個方法的逾時間隔等於呼叫這個方法的應用程式定義域的預設逾時值。This method times out after an interval that is equal to the default time-out value of the application domain in which it is called. 如果未針對應用程式定義域定義逾時值,則使用值 InfiniteMatchTimeout,使方法不會逾時。If a time-out value has not been defined for the application domain, the value InfiniteMatchTimeout, which prevents the method from timing out, is used. 用來抓取多個模式相符專案的建議Matches(String, String, RegexOptions, TimeSpan)靜態方法是, 可讓您指定逾時間隔。The recommended static method for retrieving multiple pattern matches is Matches(String, String, RegexOptions, TimeSpan), which lets you specify the time-out interval.

另請參閱

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.

public:
 static System::Text::RegularExpressions::MatchCollection ^ Matches(System::String ^ input, System::String ^ pattern, System::Text::RegularExpressions::RegexOptions options);
public static System.Text.RegularExpressions.MatchCollection Matches (string input, string pattern, System.Text.RegularExpressions.RegexOptions options);
static member Matches : string * string * System.Text.RegularExpressions.RegexOptions -> System.Text.RegularExpressions.MatchCollection
Public Shared Function Matches (input As String, pattern As String, options As RegexOptions) As MatchCollection

參數

input
String String String String

用來搜尋比對的字串。The string to search for a match.

pattern
String String String String

要比對的規則運算式模式。The regular expression pattern to match.

options
RegexOptions RegexOptions RegexOptions RegexOptions

列舉值的位元組合,這些值會指定用於比對的選項。A bitwise combination of the enumeration values that specify options for matching.

傳回

搜尋之後找到的 Match 物件集合。A collection of the Match objects found by the search. 如果找不到相符的項目,此方法會傳回空集合物件。If no matches are found, the method returns an empty collection object.

例外狀況

發生規則運算式剖析錯誤。A regular expression parsing error occurred.

inputpatternnullinput or pattern is null.

options 不是 RegexOptions 值的有效位元組合。options is not a valid bitwise combination of RegexOptions values.

範例

下列範例會呼叫Matches(String, String)方法, 以識別以 "es" 結尾之句子中的任何單字, 然後Matches(String, String, RegexOptions)呼叫方法來執行模式與輸入字串的不區分大小寫比較。The following example calls the Matches(String, String) method to identify any word in a sentence that ends in "es", and then calls the Matches(String, String, RegexOptions) method to perform a case-insensitive comparison of the pattern with the input string. 如輸出所示, 這兩個方法會傳回不同的結果。As the output shows, the two methods return different results.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"\b\w+es\b";
      string sentence = "NOTES: Any notes or comments are optional.";
      
      // Call Matches method without specifying any options.
      foreach (Match match in Regex.Matches(sentence, pattern))
         Console.WriteLine("Found '{0}' at position {1}", 
                           match.Value, match.Index);
      Console.WriteLine();

      // Call Matches method for case-insensitive matching.
      foreach (Match match in Regex.Matches(sentence, pattern, RegexOptions.IgnoreCase))
         Console.WriteLine("Found '{0}' at position {1}", 
                           match.Value, match.Index);
   }
}
// The example displays the following output:
//       Found 'notes' at position 11
//       
//       Found 'NOTES' at position 0
//       Found 'notes' at position 11
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim pattern As String = "\b\w+es\b"
      Dim sentence As String = "NOTES: Any notes or comments are optional."
      
      ' Call Matches method without specifying any options.
      For Each match As Match In Regex.Matches(sentence, pattern)
         Console.WriteLine("Found '{0}' at position {1}", match.Value, match.Index)
      Next
      Console.WriteLine()
      
      ' Call Matches method for case-insensitive matching.
      For Each match As Match In Regex.Matches(sentence, pattern, RegexOptions.IgnoreCase)
         Console.WriteLine("Found '{0}' at position {1}", match.Value, match.Index)
      Next
   End Sub
End Module
' The example displays the following output:
'       Found 'notes' at position 11
'       
'       Found 'NOTES' at position 0
'       Found 'notes' at position 11

規則運算式模式 \b\w+es\b 的定義如下表所示。The regular expression pattern \b\w+es\b is defined as shown in the following table.

模式Pattern 說明Description
\b 開始字緣比對。Begin the match at a word boundary.
\w+ 比對一個或多個文字字元。Match one or more word characters.
es 符合常值字串 "es"。Match the literal string "es".
\b 結束字緣比對。End the match at a word boundary.

備註

方法與Match(String, String, RegexOptions)方法類似, 不同之處在于它會傳回在輸入字串中找到之所有相符專案的相關資訊, 而不是單一相符專案。 Matches(String, String, RegexOptions)The Matches(String, String, RegexOptions) method is similar to the Match(String, String, RegexOptions) method, except that it returns information about all the matches found in the input string, instead of a single match. 它相當於下列程式碼:It is equivalent to the following code:

Match match = Regex.Match(input, pattern, options);
while (match.Success) {
      // Handle match here...

      match = match.NextMatch();
}  
Dim match As Match = Regex.Match(input, pattern, options)
Do While match.Success
      ' Handle match here...

      match = match.NextMatch()
Loop  

靜態Matches方法相當於使用指定的正Regex則運算式模式來建立物件, 並呼叫實例方法MatchesThe static Matches methods are equivalent to constructing a Regex object with the specified regular expression pattern and calling the instance method Matches.

pattern 參數包含規則運算式語言項目,以透過符號描述要比對的字串。The pattern parameter consists of regular expression language elements that symbolically describe the string to match. 如需正則運算式的詳細資訊, 請參閱.NET Framework 正則運算式正則運算式語言-快速參考For more information about regular expressions, see .NET Framework Regular Expressions and Regular Expression Language - Quick Reference.

方法會使用「延遲評估」來填入MatchCollection傳回的物件。 MatchesThe Matches method uses lazy evaluation to populate the returned MatchCollection object. 存取這個集合的成員 (例如 MatchCollection.CountMatchCollection.CopyTo) 會導致立即填入集合。Accessing members of this collection such as MatchCollection.Count and MatchCollection.CopyTo causes the collection to be populated immediately. 若要利用延遲評估, 您應該使用結構 (例如和foreach C# For Each中的) 來逐一查看集合 .。NextTo take advantage of lazy evaluation, you should iterate the collection by using a construct such as foreach in C# and For EachNext 在 Visual Basic 中。in Visual Basic.

因為它的延遲評估, 所以呼叫Matches(String, String)方法並不會RegexMatchTimeoutException擲回例外狀況。Because of its lazy evaluation, calling the Matches(String, String) method does not throw a RegexMatchTimeoutException exception. 不過, 在此方法所傳回的MatchCollection物件上執行作業時, 如果逾時間隔是由目前應用程式域的 "REGEX_DEFAULT_MATCH_TIMEOUT" 屬性和比對作業所定義, 就會擲回例外狀況。超過此逾時間隔。However, the exception is thrown when an operation is performed on the MatchCollection object returned by this method, if a time-out interval is defined by the "REGEX_DEFAULT_MATCH_TIMEOUT" property of the current application domain and a matching operation exceeds this time-out interval.

給呼叫者的注意事項

這個方法的逾時間隔等於呼叫這個方法的應用程式定義域的預設逾時值。This method times out after an interval that is equal to the default time-out value of the application domain in which it is called. 如果未針對應用程式定義域定義逾時值,則使用值 InfiniteMatchTimeout,使方法不會逾時。If a time-out value has not been defined for the application domain, the value InfiniteMatchTimeout, which prevents the method from timing out, is used. 用來抓取多個模式相符專案的建議Matches(String, String, RegexOptions, TimeSpan)靜態方法是, 可讓您設定逾時間隔。The recommended static method for retrieving multiple pattern matches is Matches(String, String, RegexOptions, TimeSpan), which lets you set the time-out interval.

另請參閱

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.

public:
 static System::Text::RegularExpressions::MatchCollection ^ Matches(System::String ^ input, System::String ^ pattern, System::Text::RegularExpressions::RegexOptions options, TimeSpan matchTimeout);
public static System.Text.RegularExpressions.MatchCollection Matches (string input, string pattern, System.Text.RegularExpressions.RegexOptions options, TimeSpan matchTimeout);
static member Matches : string * string * System.Text.RegularExpressions.RegexOptions * TimeSpan -> System.Text.RegularExpressions.MatchCollection
Public Shared Function Matches (input As String, pattern As String, options As RegexOptions, matchTimeout As TimeSpan) As MatchCollection

參數

input
String String String String

用來搜尋比對的字串。The string to search for a match.

pattern
String String String String

要比對的規則運算式模式。The regular expression pattern to match.

options
RegexOptions RegexOptions RegexOptions RegexOptions

列舉值的位元組合,這些值會指定用於比對的選項。A bitwise combination of the enumeration values that specify options for matching.

matchTimeout
TimeSpan TimeSpan TimeSpan TimeSpan

逾時間隔,若要表示此方法不應逾時則為 InfiniteMatchTimeoutA time-out interval, or InfiniteMatchTimeout to indicate that the method should not time out.

傳回

搜尋之後找到的 Match 物件集合。A collection of the Match objects found by the search. 如果找不到相符的項目,此方法會傳回空集合物件。If no matches are found, the method returns an empty collection object.

例外狀況

發生規則運算式剖析錯誤。A regular expression parsing error occurred.

inputpatternnullinput or pattern is null.

options 不是 RegexOptions 值的有效位元組合。options is not a valid bitwise combination of RegexOptions values.

-或--or- matchTimeout 為負數、零或約大於 24 天。matchTimeout is negative, zero, or greater than approximately 24 days.

範例

下列範例會呼叫Matches(String, String, RegexOptions, TimeSpan)方法, 以執行區分大小寫的比較, 以符合以 "es" 結尾之句子中的任何單字。The following example calls the Matches(String, String, RegexOptions, TimeSpan) method to perform a case-sensitive comparison that matches any word in a sentence that ends in "es". 然後, 它會Matches(String, String, RegexOptions, TimeSpan)呼叫方法來執行模式與輸入字串的不區分大小寫比較。It then calls the Matches(String, String, RegexOptions, TimeSpan) method to perform a case-insensitive comparison of the pattern with the input string. 在這兩種情況下, 逾時間隔會設定為一秒。In both cases, the time-out interval is set to one second. 如輸出所示, 這兩個方法會傳回不同的結果。As the output shows, the two methods return different results.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"\b\w+es\b";
      string sentence = "NOTES: Any notes or comments are optional.";
      
      // Call Matches method without specifying any options.
      try {
         foreach (Match match in Regex.Matches(sentence, pattern,
                                               RegexOptions.None,
                                               TimeSpan.FromSeconds(1)))
            Console.WriteLine("Found '{0}' at position {1}", 
                              match.Value, match.Index);
      }
      catch (RegexMatchTimeoutException) {
         // Do Nothing: Assume that timeout represents no match.
      }
      Console.WriteLine();

      // Call Matches method for case-insensitive matching.
      try { 
         foreach (Match match in Regex.Matches(sentence, pattern, RegexOptions.IgnoreCase))
            Console.WriteLine("Found '{0}' at position {1}", 
                              match.Value, match.Index);
      }
      catch (RegexMatchTimeoutException) {}
   }
}
// The example displays the following output:
//       Found 'notes' at position 11
//       
//       Found 'NOTES' at position 0
//       Found 'notes' at position 11
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim pattern As String = "\b\w+es\b"
      Dim sentence As String = "NOTES: Any notes or comments are optional."
      
      ' Call Matches method without specifying any options.
      For Each match As Match In Regex.Matches(sentence, pattern, 
                                               RegexOptions.None, 
                                               TimeSpan.FromSeconds(1))
         Try
            Console.WriteLine("Found '{0}' at position {1}", match.Value, match.Index)
         Catch e As RegexMatchTimeoutException
            ' Do Nothing: Assume that timeout represents no match.
         End Try
      Next
      Console.WriteLine()
      
      ' Call Matches method for case-insensitive matching.
      Try
         For Each match As Match In Regex.Matches(sentence, pattern, 
                                                  RegexOptions.IgnoreCase,
                                                  TimeSpan.FromSeconds(1))
            Console.WriteLine("Found '{0}' at position {1}", match.Value, match.Index)
         Next
      Catch de As RegexMatchTimeoutException
         ' Do Nothing: Assume that timeout represents no match.
      End Try
   End Sub
End Module
' The example displays the following output:
'       Found 'notes' at position 11
'       
'       Found 'NOTES' at position 0
'       Found 'notes' at position 11

規則運算式模式 \b\w+es\b 的定義如下表所示。The regular expression pattern \b\w+es\b is defined as shown in the following table.

模式Pattern 說明Description
\b 開始字緣比對。Begin the match at a word boundary.
\w+ 比對一個或多個文字字元。Match one or more word characters.
es 符合常值字串 "es"。Match the literal string "es".
\b 結束字緣比對。End the match at a word boundary.

備註

方法與Match(String, String, RegexOptions, TimeSpan)方法類似, 不同之處在于它會傳回在輸入字串中找到之所有相符專案的相關資訊, 而不是單一相符專案。 Matches(String, String, RegexOptions, TimeSpan)The Matches(String, String, RegexOptions, TimeSpan) method is similar to the Match(String, String, RegexOptions, TimeSpan) method, except that it returns information about all the matches found in the input string, instead of a single match. 它相當於下列程式碼:It is equivalent to the following code:

   try {
      Match match = Regex.Match(input, pattern, options,
                                TimeSpan.FromSeconds(1));
      while (match.Success) {
            // Handle match here...

            match = match.NextMatch();
      }  
   }
   catch (RegexMatchTimeoutException) {
      // Do nothing: assume that exception represents no match.
   }
   Try
      Dim match As Match = Regex.Match(input, pattern, options, 
                                       TimeSpan.FromSeconds(1))
      Do While match.Success
            ' Handle match here...

            match = match.NextMatch()
      Loop  
   Catch e As RegexMatchTimeoutException
      ' Do nothing: assume that exception represents no match.
   End Try   

靜態Matches方法相當於使用指定的正Regex則運算式模式來建立物件, 並呼叫實例方法MatchesThe static Matches methods are equivalent to constructing a Regex object with the specified regular expression pattern and calling the instance method Matches.

pattern 參數包含規則運算式語言項目,以透過符號描述要比對的字串。The pattern parameter consists of regular expression language elements that symbolically describe the string to match. 如需正則運算式的詳細資訊, 請參閱.NET Framework 正則運算式正則運算式語言-快速參考For more information about regular expressions, see .NET Framework Regular Expressions and Regular Expression Language - Quick Reference.

方法會使用「延遲評估」來填入MatchCollection傳回的物件。 MatchesThe Matches method uses lazy evaluation to populate the returned MatchCollection object. 存取這個集合的成員 (例如 MatchCollection.CountMatchCollection.CopyTo) 會導致立即填入集合。Accessing members of this collection such as MatchCollection.Count and MatchCollection.CopyTo causes the collection to be populated immediately. 若要利用延遲評估, 您應該使用結構 (例如和foreach C# For Each中的) 來逐一查看集合 .。NextTo take advantage of lazy evaluation, you should iterate the collection by using a construct such as foreach in C# and For EachNext 在 Visual Basic 中。in Visual Basic.

因為它的延遲評估, 所以呼叫Matches方法並不會RegexMatchTimeoutException擲回例外狀況。Because of its lazy evaluation, calling the Matches method does not throw a RegexMatchTimeoutException exception. 不過, 如果比對作業超過參數所MatchCollection matchTimeout指定的這個逾時間隔, 在此方法所傳回的物件上執行作業時, 就會擲回例外狀況 (exception)。However, an exception is thrown when an operation is performed on the MatchCollection object returned by this method, if a matching operation exceeds this time-out interval specified by thematchTimeout parameter.

給呼叫者的注意事項

我們建議您將matchTimeout參數設定為適當的值, 例如兩秒。We recommend that you set the matchTimeout parameter to an appropriate value, such as two seconds. 如果您藉由指定InfiniteMatchTimeout來停用超時, 則正則運算式引擎可提供稍微較佳的效能。If you disable time-outs by specifying InfiniteMatchTimeout, the regular expression engine offers slightly better performance. 不過, 只有在下列情況下, 您才應該停用超時:However, you should disable time-outs only under the following conditions: -當正則運算式所處理的輸入衍生自已知且受信任的來源, 或包含靜態文字時。- When the input processed by a regular expression is derived from a known and trusted source or consists of static text. 這會排除使用者動態輸入的文字。This excludes text that has been dynamically input by users.

-當正則運算式模式經過徹底測試, 以確保它能有效率地處理相符、不相符和接近的相符專案。- When the regular expression pattern has been thoroughly tested to ensure that it efficiently handles matches, non-matches, and near matches.

-當正則運算式模式未包含任何已知在處理接近相符專案時造成過多回溯的語言元素時。- When the regular expression pattern contains no language elements that are known to cause excessive backtracking when processing a near match.

另請參閱

適用於