Edit

Share via


Regex.Matches Method

Definition

Searches an input string for all occurrences of a regular expression and returns all the matches.

Overloads

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, String, RegexOptions)

Searches the specified input string for all occurrences of a specified regular expression, using the specified matching options.

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)

Searches the specified input string for all occurrences of a regular expression.

Matches(String, String)

Searches the specified input string for all occurrences of a specified regular expression.

Matches(String, String, RegexOptions, TimeSpan)

Source:
Regex.Match.cs
Source:
Regex.Match.cs
Source:
Regex.Match.cs

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

Parameters

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

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

Returns

A collection of the Match objects found by the search. If no matches are found, the method returns an empty collection object.

Exceptions

A regular expression parsing error occurred.

input or pattern is null.

options is not a valid bitwise combination of RegexOptions values.

-or-

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

Examples

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

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.

Remarks

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

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 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 Each...Next 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 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.

See also

Applies to

Matches(String, String, RegexOptions)

Source:
Regex.Match.cs
Source:
Regex.Match.cs
Source:
Regex.Match.cs

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

Parameters

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.

Returns

A collection of the Match objects found by the search. If no matches are found, the method returns an empty collection object.

Exceptions

A regular expression parsing error occurred.

input or pattern is null.

options is not a valid bitwise combination of RegexOptions values.

Examples

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

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.

Remarks

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

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 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 Each...Next in Visual Basic.

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

Notes to Callers

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. 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. The recommended static method for retrieving multiple pattern matches is Matches(String, String, RegexOptions, TimeSpan), which lets you set the time-out interval.

See also

Applies to

Matches(String, Int32)

Source:
Regex.Match.cs
Source:
Regex.Match.cs
Source:
Regex.Match.cs

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

Parameters

input
String

The string to search for a match.

startat
Int32

The character position in the input string at which to start the search.

Returns

A collection of the Match objects found by the search. If no matches are found, the method returns an empty collection object.

Exceptions

input is null.

startat is less than zero or greater than the length of input.

Examples

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

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.

Remarks

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

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.

For more details about startat, see the Remarks section of Match(String, Int32).

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 Each...Next in Visual Basic.

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

See also

Applies to

Matches(String)

Source:
Regex.Match.cs
Source:
Regex.Match.cs
Source:
Regex.Match.cs

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

Parameters

input
String

The string to search for a match.

Returns

A collection of the Match objects found by the search. If no matches are found, the method returns an empty collection object.

Exceptions

input is null.

Examples

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

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.

Remarks

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.

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.

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 Each...Next in Visual Basic.

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

See also

Applies to

Matches(String, String)

Source:
Regex.Match.cs
Source:
Regex.Match.cs
Source:
Regex.Match.cs

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

Parameters

input
String

The string to search for a match.

pattern
String

The regular expression pattern to match.

Returns

A collection of the Match objects found by the search. If no matches are found, the method returns an empty collection object.

Exceptions

A regular expression parsing error occurred.

input or pattern is null.

Examples

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

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.

Remarks

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

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 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 Each...Next in Visual Basic.

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

Notes to Callers

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. 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. The recommended static method for retrieving multiple pattern matches is Matches(String, String, RegexOptions, TimeSpan), which lets you specify the time-out interval.

See also

Applies to