Regex.Matches 方法

定义

在输入字符串中搜索正则表达式的所有匹配项并返回所有匹配。Searches an input string for all occurrences of a regular expression and returns all the matches.

重载

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.

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

要搜索匹配项的字符串。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.

异常

inputnullinput is null.

示例

下面的示例使用 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.

注解

Matches(String) 方法与 Match(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.

Matches 方法使用延迟计算来填充返回的 MatchCollection 对象。The 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 in 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 口。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)

从字符串中的指定起始位置开始,在指定的输入字符串中搜索正则表达式的所有匹配项。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

要搜索匹配项的字符串。The string to search for a match.

startat
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.

异常

inputnullinput is null.

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.

注解

Matches(String, Int32) 方法与 Match(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.

Matches 方法使用延迟计算来填充返回的 MatchCollection 对象。The 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 in 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 口。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)

在指定的输入字符串中搜索指定的正则表达式的所有匹配项。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

要搜索匹配项的字符串。The string to search for a match.

pattern
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.

注解

Matches(String, String) 方法与 Match(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 对象,并 Matches调用实例方法。The 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.

Matches 方法使用延迟计算来填充返回的 MatchCollection 对象。The 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 in 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 口。in Visual Basic.

由于其延迟计算,调用 Matches(String, String) 方法不会引发 RegexMatchTimeoutException 异常。Because of its lazy evaluation, calling the Matches(String, String) method does not throw a RegexMatchTimeoutException exception. 但是,如果在当前应用程序域的 "REGEX_DEFAULT_MATCH_TIMEOUT" 属性定义了超时间隔并且匹配操作超过此超时间隔,则在此方法返回的 MatchCollection 对象上执行操作时,将引发异常。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)

使用指定的匹配选项在指定的输入字符串中搜索指定的正则表达式的所有匹配项。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

要搜索匹配项的字符串。The string to search for a match.

pattern
String

要匹配的正则表达式模式。The regular expression pattern to match.

options
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.

注解

Matches(String, String, RegexOptions) 方法与 Match(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 对象,并 Matches调用实例方法。The 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.

Matches 方法使用延迟计算来填充返回的 MatchCollection 对象。The 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 in 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 口。in Visual Basic.

由于其延迟计算,调用 Matches(String, String) 方法不会引发 RegexMatchTimeoutException 异常。Because of its lazy evaluation, calling the Matches(String, String) method does not throw a RegexMatchTimeoutException exception. 但是,如果在当前应用程序域的 "REGEX_DEFAULT_MATCH_TIMEOUT" 属性定义了超时间隔并且匹配操作超过此超时间隔,则在此方法返回的 MatchCollection 对象上执行操作时,将引发异常。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)

使用指定的匹配选项和超时间隔在指定的输入字符串中搜索指定的正则表达式的所有匹配项。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

要搜索匹配项的字符串。The string to search for a match.

pattern
String

要匹配的正则表达式模式。The regular expression pattern to match.

options
RegexOptions

枚举值的按位组合,这些枚举值指定用于匹配的选项。A bitwise combination of the enumeration values that specify options for matching.

matchTimeout
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. 在这两种情况下,超时间隔设置为1秒。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.

注解

Matches(String, String, RegexOptions, TimeSpan) 方法与 Match(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 对象,并 Matches调用实例方法。The 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.

Matches 方法使用延迟计算来填充返回的 MatchCollection 对象。The 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 in 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 口。in Visual Basic.

由于其延迟计算,调用 Matches 方法不会引发 RegexMatchTimeoutException 异常。Because of its lazy evaluation, calling the Matches method does not throw a RegexMatchTimeoutException exception. 但是,如果匹配操作超过matchTimeout 参数所指定的超时间隔,则在此方法返回的 MatchCollection 对象上执行操作时,将引发异常。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.

另请参阅

适用于