Regex.Match Method (String)

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

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

public Match Match (
	string input
public Match Match (
	String input
public function Match (
	input : String
) : Match
Not applicable.



The string to search for a match.

Return Value

A regular expression Match object.

Exception typeCondition


input is a null reference (Nothing in Visual Basic).

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

string text = "One car red car blue car";
string pat = @"(\w+)\s+(car)";
// Compile the regular expression.
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 code produces output similar to the following; 
   //results may vary based on the computer/file structure/etc.:
   //Capture0='One', Position=0
   //Capture0='car', Position=4
   //Capture0='red', Position=8
   //Capture0='car', Position=12
   //Capture0='blue', Position=16
   //Capture0='car', Position=21

Windows 98, Windows Server 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0, 1.0

XNA Framework

Supported in: 1.0

Community Additions