Regex.Matches Method (String, String, RegexOptions, TimeSpan)

.NET Framework 4.5

Searches the specified input string for all occurrences of a specified regular expression, using the specified matching options and time-out interval.

Namespace:  System.Text.RegularExpressions
Assembly:  System (in System.dll)

public static MatchCollection Matches(
	string input,
	string pattern,
	RegexOptions options,
	TimeSpan matchTimeout
)

Parameters

input
Type: System.String

The string to search for a match.

pattern
Type: System.String

The regular expression pattern to match.

options
Type: System.Text.RegularExpressions.RegexOptions

A bitwise combination of the enumeration values that specify options for matching.

matchTimeout
Type: System.TimeSpan

A time-out interval, or Regex.InfiniteMatchTimeout to indicate that the method should not time out.

Return Value

Type: System.Text.RegularExpressions.MatchCollection
A collection of the Match objects found by the search. If no matches are found, the method returns an empty collection object.

ExceptionCondition
ArgumentException

A regular expression parsing error occurred.

ArgumentNullException

input or pattern is null.

ArgumentOutOfRangeException

options is not a valid bitwise combination of RegexOptions values.

-or-

matchTimeout is negative, zero, or greater than approximately 24 days.

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

The static Matches methods are equivalent to constructing a Regex object with the specified regular expression pattern and calling the instance method Matches.

The pattern parameter consists of regular expression language elements that symbolically describe the string to match. For more information about regular expressions, see .NET Framework Regular Expressions and Regular Expression Language - Quick Reference.

The Matches method uses lazy evaluation to populate the returned MatchCollection object. Accessing members of this collection such as MatchCollection.Count and MatchCollection.CopyTo causes the collection to be populated immediately. To 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.

Because of its lazy evaluation, calling the Matches method does not throw a RegexMatchTimeoutException 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.

Notes to Callers

We recommend that you set the matchTimeout parameter to an appropriate value, such as two seconds. If you disable time-outs by specifying Regex.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.

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

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

Match the literal string "es".

\b

End the match at a word boundary.

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5

.NET for Windows Store apps

Supported in: Windows 8

.NET for Windows Phone apps

Supported in: Windows Phone 8.1, Windows Phone 8, Silverlight 8.1

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft