This documentation is archived and is not being maintained.

Match.NextMatch Method

Returns a new Match with the results for the next match, starting at the position at which the last match ended (at the character beyond the last matched character).

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

public Match NextMatch ()
public Match NextMatch ()
public function NextMatch () : Match
Not applicable.

Return Value

The next regular expression Match object.

This function is similar to calling Match again and passing (Index+Length) as the new starting position, but it differs from calling Match directly because it handles zero-length match cases in a way that guarantees progress to the end of the string.

The following example uses the NextMatch method to capture regular expression matches beyond the first.

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.:
   //
   //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

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