Regex.Match Method

Definition

Overloads

Match(String, String, RegexOptions)

Searches the input string for the first occurrence of the specified regular expression, using the specified matching options.

Match(String, Int32, Int32)

Searches the input string for the first occurrence of a regular expression, beginning at the specified starting position and searching only the specified number of characters.

Match(String, String, RegexOptions, TimeSpan)

Searches the input string for the first occurrence of the specified regular expression, using the specified matching options and time-out interval.

Match(String, Int32)

Searches the input string for the first occurrence of a regular expression, beginning at the specified starting position in the string.

Match(String)

Searches the specified input string for the first occurrence of the regular expression specified in the Regex constructor.

Match(String, String)

Searches the specified input string for the first occurrence of the specified regular expression.

Match(String, String, RegexOptions)

Searches the input string for the first occurrence of the specified regular expression, using the specified matching options.

public static System.Text.RegularExpressions.Match Match (string input, string pattern, System.Text.RegularExpressions.RegexOptions options);
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 provide options for matching.

Returns

An object that contains information about the match.

Exceptions

A regular expression parsing error occurred.

input or pattern is null.

options is not a valid bitwise combination of RegexOptions values.

A time-out occurred. For more information about time-outs, see the Remarks section.

Examples

The following example defines a regular expression that matches words beginning with the letter "a". It uses the RegexOptions.IgnoreCase option to ensure that the regular expression locates words beginning with both an uppercase "a" and a lowercase "a".

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"\ba\w*\b";
      string input = "An extraordinary day dawns with each new day.";
      Match m = Regex.Match(input, pattern, RegexOptions.IgnoreCase);
      if (m.Success)
         Console.WriteLine("Found '{0}' at position {1}.", m.Value, m.Index);
   }
}
// The example displays the following output:
//        Found 'An' at position 0.
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim pattern As String = "\ba\w*\b"
      Dim input As String = "An extraordinary day dawns with each new day."
      Dim m As Match = Regex.Match(input, pattern, RegexOptions.IgnoreCase)
      If m.Success Then
         Console.WriteLine("Found '{0}' at position {1}.", m.Value, m.Index)
      End If
   End Sub
End Module
' The example displays the following output:
'       Found 'An' at position 0.

The regular expression pattern \ba\w*\b is interpreted as shown in the following table.

Pattern Description
\b Begin the match at a word boundary.
a Match the character "a".
\w* Match zero, one, or more word characters.
\b End the match at a word boundary.

Remarks

The Match(String, String, RegexOptions) method returns the first substring that matches a regular expression pattern in an input string. For information about the language elements used to build a regular expression pattern, see Regular Expression Language - Quick Reference.

The static Match(String, String, RegexOptions) method is equivalent to constructing a Regex object with the Regex(String, RegexOptions) constructor and calling the instance Match(String) method.

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.

You can determine whether the regular expression pattern has been found in the input string by checking the value of the returned Match object's Success property. If a match is found, the returned Match object's Value property contains the substring from input that matches the regular expression pattern. If no match is found, its value is String.Empty.

This method returns the first substring found in input that matches the regular expression pattern. You can retrieve subsequent matches by repeatedly calling the returned Match object's NextMatch method. You can also retrieve all matches in a single method call by calling the Regex.Matches(String, String, RegexOptions) method.

The RegexMatchTimeoutException exception is thrown if the execution time of the matching operation exceeds the time-out interval specified for the application domain in which the method is called. If no time-out is defined in the application domain's properties, or if the time-out value is Regex.InfiniteMatchTimeout, no exception is thrown.

Match(String, Int32, Int32)

Searches the input string for the first occurrence of a regular expression, beginning at the specified starting position and searching only the specified number of characters.

public System.Text.RegularExpressions.Match Match (string input, int beginning, int length);
Parameters
input
String

The string to search for a match.

beginning
Int32

The zero-based character position in the input string that defines the leftmost position to be searched.

length
Int32

The number of characters in the substring to include in the search.

Returns

An object that contains information about the match.

Exceptions

input is null.

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

-or-

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

-or-

beginning+length–1 identifies a position that is outside the range of input.

A time-out occurred. For more information about time-outs, see the Remarks section.

Remarks

The Match(String, Int32, Int32) method returns the first substring that matches a regular expression pattern in a portion of an input string. For information about the language elements used to build a regular expression pattern, see Regular Expression Language - Quick Reference.

The regular expression pattern for which the Match(String, Int32, 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.

The Match(String, Int32, Int32) method searches the portion of input defined by the beginning and length parameters for the regular expression pattern. beginning always defines the index of the leftmost character to include in the search, and length defines the maximum number of characters to search. Together, they define the range of the search. If the search proceeds from left to right (the default), the regular expression engine searches from the character at index beginning to the character at index beginning + length – 1. If the regular expression engine was instantiated by using the RegexOptions.RightToLeft option so that the search proceeds from right to left, the regular expression engine searches from the character at index beginning + length – 1 to the character at index beginning. This method returns the first match that it finds within this range. You can retrieve subsequent matches by repeatedly calling the returned Match object's Match.NextMatch method.

You can determine whether the regular expression pattern has been found in the input string by checking the value of the returned Match object's Success property. If a match is found, the returned Match object's Value property contains the substring from input that matches the regular expression pattern. If no match is found, its value is String.Empty.

The RegexMatchTimeoutException exception is thrown if the execution time of the matching operation exceeds the time-out interval specified by the Regex.Regex(String, RegexOptions, TimeSpan) constructor. If you do not set a time-out value when you call the constructor, the exception is thrown if the operation exceeds any time-out value established for the application domain in which the Regex object is created. If no time-out is defined in the Regex constructor call or in the application domain's properties, or if the time-out value is Regex.InfiniteMatchTimeout, no exception is thrown.

Match(String, String, RegexOptions, TimeSpan)

Searches the input string for the first occurrence of the specified regular expression, using the specified matching options and time-out interval.

public static System.Text.RegularExpressions.Match Match (string input, string pattern, System.Text.RegularExpressions.RegexOptions options, TimeSpan matchTimeout);
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 provide options for matching.

matchTimeout
TimeSpan

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

Returns

An object that contains information about the match.

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.

A time-out occurred. For more information about time-outs, see the Remarks section.

Remarks

The Match(String, String, RegexOptions, TimeSpan) method returns the first substring that matches a regular expression pattern in an input string. For information about the language elements used to build a regular expression pattern, see Regular Expression Language - Quick Reference.

The static Match(String, String, RegexOptions, TimeSpan) method is equivalent to constructing a Regex object with the Regex(String, RegexOptions, TimeSpan) constructor and calling the instance Match(String) method.

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.

You can determine whether the regular expression pattern has been found in the input string by checking the value of the returned Match object's Success property. If a match is found, the returned Match object's Value property contains the substring from input that matches the regular expression pattern. If no match is found, its value is String.Empty.

This method returns the first substring found in input that matches the regular expression pattern. You can retrieve subsequent matches by repeatedly calling the returned Match object's NextMatch method. You can also retrieve all matches in a single method call by calling the Regex.Matches(String, String, RegexOptions) method.

The matchTimeout parameter specifies how long a pattern matching method should try to find a match before it times out. Setting a time-out interval prevents regular expressions that rely on excessive backtracking from appearing to stop responding when they process input that contains near matches. For more information, see Best Practices for Regular Expressions and Backtracking. If no match is found in that time interval, the method throws a RegexMatchTimeoutException exception. matchTimeout overrides any default time-out value defined for the application domain in which the method executes.

Match(String, Int32)

Searches the input string for the first occurrence of a regular expression, beginning at the specified starting position in the string.

public System.Text.RegularExpressions.Match Match (string input, int startat);
Parameters
input
String

The string to search for a match.

startat
Int32

The zero-based character position at which to start the search.

Returns

An object that contains information about the match.

Exceptions

input is null.

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

A time-out occurred. For more information about time-outs, see the Remarks section.

Remarks

The Match(String, Int32) method returns the first substring that matches a regular expression pattern, starting at or after the startat character position, in an input string. For information about the language elements used to build a regular expression pattern, see Regular Expression Language - Quick Reference.

The regular expression pattern for which the Match(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.

You can optionally specify a starting position in the string by using the startat parameter. When the regular expression engine parses from left to right (the default), the match and the scan move rightward, starting at the character specified in startat. When the regular expression engine parses from right to left (when the regular expression pattern is constructed with the RegexOptions.RightToLeft option), the match and scan move in the opposite direction and begin with the character at startat -1. If you do not specify a starting position, the search begins at the default startat position. If the regular expression searches from left to right, the default startat position is at the left end of input; if it searches from right to left, the default startat position is at the right end of input.

If you want to restrict a match so that it begins at a particular character position in the string and the regular expression engine does not scan the remainder of the string for a match, anchor the regular expression with a \G (at the left for a left-to-right pattern, or at the right for a right-to-left pattern). This restricts the match so it must start exactly at startat.

You can determine whether the regular expression pattern has been found in the input string by checking the value of the returned Match object's Success property. If a match is found, the returned Match object's Value property contains the substring from input that matches the regular expression pattern. If no match is found, its value is String.Empty.

This method returns the first substring found at or after the startat character position in input that matches the regular expression pattern. You can retrieve subsequent matches by repeatedly calling the returned Match object's Match.NextMatch method. You can also retrieve all matches in a single method call by calling the Regex.Matches(String, Int32) method.

The RegexMatchTimeoutException exception is thrown if the execution time of the matching operation exceeds the time-out interval specified by the Regex.Regex(String, RegexOptions, TimeSpan) constructor. If you do not set a time-out interval when you call the constructor, the exception is thrown if the operation exeeds any time-out value established for the application domain in which the Regex object is created. If no time-out is defined in the Regex constructor call or in the application domain's properties, or if the time-out value is Regex.InfiniteMatchTimeout, no exception is thrown.

Match(String)

Searches the specified input string for the first occurrence of the regular expression specified in the Regex constructor.

public System.Text.RegularExpressions.Match Match (string input);
Parameters
input
String

The string to search for a match.

Returns

An object that contains information about the match.

Exceptions

input is null.

A time-out occurred. For more information about time-outs, see the Remarks section.

Examples

The following example finds regular expression pattern matches in a string, then lists the matched groups, captures, and capture positions.

#using <System.dll>

using namespace System;
using namespace System::Text::RegularExpressions;
void main()
{
   
   String^ text = "One car red car blue car";
   String^ pat = "(\\w+)\\s+(car)";
   
   // Compile the regular expression.
   Regex^ r = gcnew Regex( pat,RegexOptions::IgnoreCase );
   
   // Match the regular expression pattern against a text string.
   Match^ m = r->Match(text);
   int matchCount = 0;
   while ( m->Success )
   {
      Console::WriteLine( "Match{0}", ++matchCount );
      for ( int i = 1; i <= 2; i++ )
      {
         Group^ g = m->Groups[ i ];
         Console::WriteLine( "Group{0}='{1}'", i, g );
         CaptureCollection^ cc = g->Captures;
         for ( int j = 0; j < cc->Count; j++ )
         {
            Capture^ c = cc[ j ];
            System::Console::WriteLine( "Capture{0}='{1}', Position={2}", j, c, c->Index );
         }
      }
      m = m->NextMatch();
   }
}  
// This example displays the following output:
//       Match1
//       Group1='One'
//       Capture0='One', Position=0
//       Group2='car'
//       Capture0='car', Position=4
//       Match2
//       Group1='red'
//       Capture0='red', Position=8
//       Group2='car'
//       Capture0='car', Position=12
//       Match3
//       Group1='blue'
//       Capture0='blue', Position=16
//       Group2='car'
//       Capture0='car', Position=21
using System;
using System.Text.RegularExpressions;

class Example 
{
   static void Main() 
   {
      string text = "One car red car blue car";
      string pat = @"(\w+)\s+(car)";

      // Instantiate the regular expression object.
      Regex r = new Regex(pat, RegexOptions.IgnoreCase);
      
      // Match the regular expression pattern against a text string.
      Match m = r.Match(text);
      int matchCount = 0;
      while (m.Success) 
      {
         Console.WriteLine("Match"+ (++matchCount));
         for (int i = 1; i <= 2; i++) 
         {
            Group g = m.Groups[i];
            Console.WriteLine("Group"+i+"='" + g + "'");
            CaptureCollection cc = g.Captures;
            for (int j = 0; j < cc.Count; j++) 
            {
               Capture c = cc[j];
               System.Console.WriteLine("Capture"+j+"='" + c + "', Position="+c.Index);
            }
         }
         m = m.NextMatch();
      }
   }
}
// This example displays the following output:
//       Match1
//       Group1='One'
//       Capture0='One', Position=0
//       Group2='car'
//       Capture0='car', Position=4
//       Match2
//       Group1='red'
//       Capture0='red', Position=8
//       Group2='car'
//       Capture0='car', Position=12
//       Match3
//       Group1='blue'
//       Capture0='blue', Position=16
//       Group2='car'
//       Capture0='car', Position=21
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim text As String = "One car red car blue car"
      Dim pattern As String = "(\w+)\s+(car)"

      ' Instantiate the regular expression object.
      Dim r As Regex = new Regex(pattern, RegexOptions.IgnoreCase)

      ' Match the regular expression pattern against a text string.
      Dim m As Match = r.Match(text)
      Dim matchcount as Integer = 0
      Do While m.Success
         matchCount += 1
         Console.WriteLine("Match" & (matchCount))
         Dim i As Integer
         For i = 1 to 2
            Dim g as Group = m.Groups(i)
            Console.WriteLine("Group" & i & "='" & g.ToString() & "'")
            Dim cc As CaptureCollection = g.Captures
            Dim j As Integer 
            For j = 0 to cc.Count - 1
      	      Dim c As Capture = cc(j)
               Console.WriteLine("Capture" & j & "='" & c.ToString() _
                  & "', Position=" & c.Index)
            Next 
         Next 
         m = m.NextMatch()
      Loop
   End Sub
End Module
' This example displays the following output:
'       Match1
'       Group1='One'
'       Capture0='One', Position=0
'       Group2='car'
'       Capture0='car', Position=4
'       Match2
'       Group1='red'
'       Capture0='red', Position=8
'       Group2='car'
'       Capture0='car', Position=12
'       Match3
'       Group1='blue'
'       Capture0='blue', Position=16
'       Group2='car'
'       Capture0='car', Position=21

The regular expression pattern (\w+)\s+(car) matches occurrences of the word "car" along with the word that precedes it. It is interpreted as shown in the following table.

Pattern Description
(\w+) Match one or more word characters. This is the first capturing group.
\s+ Match one or more white-space characters.
(car) Match the literal string "car". This is the second capturing group.

Remarks

The Match(String) method returns the first substring that matches a regular expression pattern in an input string. For information about the language elements used to build a regular expression pattern, see Regular Expression Language - Quick Reference.

You can determine whether the regular expression pattern has been found in the input string by checking the value of the returned Match object's Success property. If a match is found, the returned Match object's Value property contains the substring from input that matches the regular expression pattern. If no match is found, its value is String.Empty.

This method returns the first substring in input that matches the regular expression pattern. You can retrieve subsequent matches by repeatedly calling the returned Match object's Match.NextMatch method. You can also retrieve all matches in a single method call by calling the Regex.Matches(String) method.

The RegexMatchTimeoutException exception is thrown if the execution time of the matching operation exceeds the time-out interval specified by the Regex.Regex(String, RegexOptions, TimeSpan) constructor. If you do not set a time-out interval when you call the constructor, the exception is thrown if the operation exceeds any time-out value established for the application domain in which the Regex object is created. If no time-out is defined in the Regex constructor call or in the application domain's properties, or if the time-out value is Regex.InfiniteMatchTimeout, no exception is thrown.

Match(String, String)

Searches the specified input string for the first occurrence of the specified regular expression.

public static System.Text.RegularExpressions.Match Match (string input, string pattern);
Parameters
input
String

The string to search for a match.

pattern
String

The regular expression pattern to match.

Returns

An object that contains information about the match.

Exceptions

A regular expression parsing error occurred.

input or pattern is null.

A time-out occurred. For more information about time-outs, see the Remarks section.

Examples

The following example calls the Match(String, String) method to find the first word that contains at least one z character, and then calls the Match.NextMatch method to find any additional matches.

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "ablaze beagle choral dozen elementary fanatic " +
                     "glaze hunger inept jazz kitchen lemon minus " +
                     "night optical pizza quiz restoration stamina " +
                     "train unrest vertical whiz xray yellow zealous";
      string pattern = @"\b\w*z+\w*\b";
      Match m = Regex.Match(input, pattern);
      while (m.Success) {
         Console.WriteLine("'{0}' found at position {1}", m.Value, m.Index);
         m = m.NextMatch();
      }   
   }
}
// The example displays the following output:
//    'ablaze' found at position 0
//    'dozen' found at position 21
//    'glaze' found at position 46
//    'jazz' found at position 65
//    'pizza' found at position 104
//    'quiz' found at position 110
//    'whiz' found at position 157
//    'zealous' found at position 174
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = "ablaze beagle choral dozen elementary fanatic " +
                            "glaze hunger inept jazz kitchen lemon minus " +
                            "night optical pizza quiz restoration stamina " +
                            "train unrest vertical whiz xray yellow zealous"
      Dim pattern As String = "\b\w*z+\w*\b"
      Dim m As Match = Regex.Match(input, pattern)
      Do While m.Success 
         Console.WriteLine("'{0}' found at position {1}", m.Value, m.Index)
         m = m.NextMatch()
      Loop                      
   End Sub
End Module
' The example displays the following output:
    'ablaze' found at position 0
    'dozen' found at position 21
    'glaze' found at position 46
    'jazz' found at position 65
    'pizza' found at position 104
    'quiz' found at position 110
    'whiz' found at position 157
    'zealous' found at position 174

The regular expression pattern \b\w*z+\w*\b is interpreted as shown in the following table.

Pattern Description
\b Begin the match at a word boundary.
\w* Match zero, one, or more word characters.
z+ Match one or more occurrences of the z character.
\w* Match zero, one, or more word characters.
\b End the match at a word boundary.

Remarks

The Match(String, String) method returns the first substring that matches a regular expression pattern in an input string. For information about the language elements used to build a regular expression pattern, see Regular Expression Language - Quick Reference.

The static Match(String, String) method is equivalent to constructing a Regex object with the specified regular expression pattern and calling the instance Match(String) method. In this case, the regular expression engine caches the regular expression pattern.

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.

You can determine whether the regular expression pattern has been found in the input string by checking the value of the returned Match object's Success property. If a match is found, the returned Match object's Value property contains the substring from input that matches the regular expression pattern. If no match is found, its value is String.Empty.

This method returns the first substring in input that matches the regular expression pattern. You can retrieve subsequent matches by repeatedly calling the returned Match object's Match.NextMatch method. You can also retrieve all matches in a single method call by calling the Regex.Matches(String, String) method.

The RegexMatchTimeoutException exception is thrown if the execution time of the matching operation exceeds the time-out interval specified for the application domain in which the method is called. If no time-out is defined in the application domain's properties, or if the time-out value is Regex.InfiniteMatchTimeout, no exception is thrown.