2010-07-14 17 views
14

¿Por qué el resultado siguiente código en:¿Cómo encontrar múltiples ocurrencias con grupos regex?

hubo 1 partidos de 'la'

y no:

había 3 partidos de 'la'

using System; 
using System.Text.RegularExpressions; 

namespace TestRegex82723223 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string text = "C# is the best language there is in the world."; 
      string search = "the"; 
      Match match = Regex.Match(text, search); 
      Console.WriteLine("there was {0} matches for '{1}'", match.Groups.Count, match.Value); 
      Console.ReadLine(); 
     } 
    } 
} 

Respuesta

29
string text = "C# is the best language there is in the world."; 
string search = "the"; 
MatchCollection matches = Regex.Matches(text, search); 
Console.WriteLine("there was {0} matches for '{1}'", matches.Count, search); 
Console.ReadLine(); 
2

Match devuelve la primera coincidencia, consulte this para saber cómo obtener el resto.

En su lugar, debe usar Matches. Posteriormente, se podría utilizar:

MatchCollection matches = Regex.Matches(text, search); 
Console.WriteLine("there were {0} matches", matches.Count); 
1

Debe utilizar Regex.Matches en lugar de Regex.Match si desea devolver varias coincidencias.

Cuestiones relacionadas