Regex.Match Method
Definition
Important
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Searches an input string for a substring that matches a regular expression pattern and returns the first occurrence as a single Match object.
Overloads
Match(String) |
Searches the specified input string for the first occurrence of the regular expression specified in the Regex constructor. |
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, String) |
Searches the specified input string for the first occurrence of the specified regular expression. |
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) |
Searches the input string for the first occurrence of the specified regular expression, using the specified matching options. |
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)
- Source:
- Regex.Match.cs
- Source:
- Regex.Match.cs
- Source:
- Regex.Match.cs
Searches the specified input string for the first occurrence of the regular expression specified in the Regex constructor.
public:
System::Text::RegularExpressions::Match ^ Match(System::String ^ input);
public System.Text.RegularExpressions.Match Match (string input);
member this.Match : string -> System.Text.RegularExpressions.Match
Public Function Match (input As String) As Match
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.
See also
Applies to
Match(String, Int32)
- Source:
- Regex.Match.cs
- Source:
- Regex.Match.cs
- Source:
- Regex.Match.cs
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(System::String ^ input, int startat);
public System.Text.RegularExpressions.Match Match (string input, int startat);
member this.Match : string * int -> System.Text.RegularExpressions.Match
Public Function Match (input As String, startat As Integer) As Match
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
For more information about this API, see Supplemental API remarks for Regex.Match.
See also
Applies to
Match(String, String)
- Source:
- Regex.Match.cs
- Source:
- Regex.Match.cs
- Source:
- Regex.Match.cs
Searches the specified input string for the first occurrence of the specified regular expression.
public:
static System::Text::RegularExpressions::Match ^ Match(System::String ^ input, System::String ^ pattern);
public static System.Text.RegularExpressions.Match Match (string input, string pattern);
static member Match : string * string -> System.Text.RegularExpressions.Match
Public Shared Function Match (input As String, pattern As String) As Match
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;
namespace Examples
{
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 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.
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 a pattern match is Match(String, String), which lets you set the time-out interval.
See also
Applies to
Match(String, Int32, Int32)
- Source:
- Regex.Match.cs
- Source:
- Regex.Match.cs
- Source:
- Regex.Match.cs
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(System::String ^ input, int beginning, int length);
public System.Text.RegularExpressions.Match Match (string input, int beginning, int length);
member this.Match : string * int * int -> System.Text.RegularExpressions.Match
Public Function Match (input As String, beginning As Integer, length As Integer) As Match
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. The behavior is exactly as if the input
was effectively input.Substring(beginning, length)
, except that the index of any match is counted relative to the start of input
. This means that any anchors or zero-width assertions at the start or end of the pattern behave as if there is no input
outside of this range. For example the anchors ^
, \G
, and \A
will be satisfied at beginning
and $
and \z
will be satisfied at beginning + length - 1
.
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.
See also
Applies to
Match(String, String, RegexOptions)
- Source:
- Regex.Match.cs
- Source:
- Regex.Match.cs
- Source:
- Regex.Match.cs
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(System::String ^ input, System::String ^ pattern, System::Text::RegularExpressions::RegexOptions options);
public static System.Text.RegularExpressions.Match Match (string input, string pattern, System.Text.RegularExpressions.RegexOptions options);
static member Match : string * string * System.Text.RegularExpressions.RegexOptions -> System.Text.RegularExpressions.Match
Public Shared Function Match (input As String, pattern As String, options As RegexOptions) As Match
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;
namespace Examples
{
public class Example2
{
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 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.
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 a pattern match is Match(String, String), which lets you set the time-out interval.
See also
Applies to
Match(String, String, RegexOptions, TimeSpan)
- Source:
- Regex.Match.cs
- Source:
- Regex.Match.cs
- Source:
- Regex.Match.cs
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(System::String ^ input, System::String ^ pattern, System::Text::RegularExpressions::RegexOptions options, TimeSpan matchTimeout);
public static System.Text.RegularExpressions.Match Match (string input, string pattern, System.Text.RegularExpressions.RegexOptions options, TimeSpan matchTimeout);
static member Match : string * string * System.Text.RegularExpressions.RegexOptions * TimeSpan -> System.Text.RegularExpressions.Match
Public Shared Function Match (input As String, pattern As String, options As RegexOptions, matchTimeout As TimeSpan) As Match
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 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.
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.