Match.NextMatch Método

Definição

Retorna um novo objeto Match com os resultados para a próxima correspondência, começando na posição em que a última correspondência terminou (no caractere após o último caractere correspondente).Returns a new Match object with the results for the next match, starting at the position at which the last match ended (at the character after the last matched character).

public:
 System::Text::RegularExpressions::Match ^ NextMatch();
public System.Text.RegularExpressions.Match NextMatch ();
member this.NextMatch : unit -> System.Text.RegularExpressions.Match
Public Function NextMatch () As Match

Retornos

Match

A próxima expressão regular de correspondência.The next regular expression match.

Exceções

Ocorreu um tempo limite.A time-out occurred.

Exemplos

O exemplo a seguir usa o NextMatch método para capturar correspondências de expressão regulares além da primeira correspondência.The following example uses the NextMatch method to capture regular expression matches beyond the first match.

#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

Comentários

Esse método é semelhante à chamada Regex.Match(String, Int32) novamente e à passagem ( Index+Length ) como a nova posição inicial.This method is similar to calling Regex.Match(String, Int32) again and passing (Index+Length) as the new starting position.

Observação

Esse método não modifica a instância atual.This method does not modify the current instance. Em vez disso, ele retorna um novo Match objeto que contém informações sobre a próxima correspondência.Instead, it returns a new Match object that contains information about the next match.

A tentativa de recuperar a próxima correspondência pode lançar um RegexMatchTimeoutException se um valor de tempo limite para operações de correspondência estiver em vigor e a tentativa de encontrar a próxima correspondência exceder esse intervalo de tempo limite.Attempting to retrieve the next match may throw a RegexMatchTimeoutException if a time-out value for matching operations is in effect and the attempt to find the next match exceeds that time-out interval.

Notas aos Chamadores

Quando uma tentativa de correspondência é repetida chamando o NextMatch() método, o mecanismo de expressão regular fornece um tratamento especial de correspondências vazia.When a match attempt is repeated by calling the NextMatch() method, the regular expression engine gives empty matches special treatment. Normalmente, NextMatch() o inicia a pesquisa para a próxima correspondência exatamente onde a correspondência anterior parou.Usually, NextMatch() begins the search for the next match exactly where the previous match left off. No entanto, após uma correspondência vazia, o NextMatch() método avança por um caractere antes de tentar a próxima correspondência.However, after an empty match, the NextMatch() method advances by one character before trying the next match. Esse comportamento garante que o mecanismo de expressão regular irá progredir por meio da cadeia de caracteres.This behavior guarantees that the regular expression engine will progress through the string. Caso contrário, como uma correspondência vazia não resulta em movimento progressivo, a próxima correspondência seria iniciada exatamente no mesmo local que a correspondência anterior, e ela corresponderia à mesma cadeia de caracteres vazia repetidamente.Otherwise, because an empty match does not result in any forward movement, the next match would start in exactly the same place as the previous match, and it would match the same empty string repeatedly.

O exemplo a seguir ilustra esse cenário.The following example provides an illustration. O padrão de expressão regular a * pesquisa zero ou mais ocorrências da letra "a" na cadeia de caracteres "abaabb".The regular expression pattern a* searches for zero or more occurrences of the letter "a" in the string "abaabb". Como a saída do exemplo mostra, a pesquisa localiza seis correspondências.As the output from the example shows, the search finds six matches. A primeira tentativa de correspondência localiza o primeiro "a".The first match attempt finds the first "a". A segunda correspondência começa exatamente onde a primeira correspondência termina, antes da primeira b; Ele encontra zero ocorrências de "a" e retorna uma cadeia de caracteres vazia.The second match starts exactly where the first match ends, before the first b; it finds zero occurrences of "a" and returns an empty string. A terceira correspondência não começa exatamente onde a segunda correspondência foi finalizada, porque a segunda correspondência retornou uma cadeia de caracteres vazia.The third match does not begin exactly where the second match ended, because the second match returned an empty string. Em vez disso, ele começa um caractere mais tarde, após o primeiro "b".Instead, it begins one character later, after the first "b". A terceira correspondência localiza duas ocorrências de "a" e retorna "AA".The third match finds two occurrences of "a" and returns "aa". A primeira tentativa de correspondência começa onde a terceira correspondência terminou, antes do segundo "b", e retorna uma cadeia de caracteres vazia.The fourth match attempt begins where the third match ended, before the second "b", and returns an empty string. A quinta tentativa de correspondência avança novamente um caractere para que ele comece antes do terceiro "b" e retorne uma cadeia de caracteres vazia.The fifth match attempt again advances one character so that it begins before the third "b" and returns an empty string. A sexta correspondência começa após o último "b" e retorna uma cadeia de caracteres vazia novamente.The sixth match begins after the last "b" and returns an empty string again.

::: código Language = "CSharp" origem = "~/Samples/Snippets/Csharp/VS_Snippets_CLR_System/System.Text.RegularExpressions.Match.NextMatch/cs/nextmatch1.cs" Interactive = "try-dotnet" ID = "Snippet1":::::: código Language = "vb" origem = "~/Samples/Snippets/VisualBasic/VS_Snippets_CLR_System/System.Text.RegularExpressions.Match.NextMatch/VB/nextmatch1.vb" ID = "Snippet1"::::::code language="csharp" source="~/samples/snippets/csharp/VS_Snippets_CLR_System/system.text.regularexpressions.match.nextmatch/cs/nextmatch1.cs" interactive="try-dotnet" id="Snippet1"::: :::code language="vb" source="~/samples/snippets/visualbasic/VS_Snippets_CLR_System/system.text.regularexpressions.match.nextmatch/vb/nextmatch1.vb" id="Snippet1":::

Aplica-se a