2011-01-08 6 views
11

Tengo múltiples coincidencias Regex. ¿Cómo puedo ponerlos en una matriz y llamarlos a cada uno individualmente, por ejemplo ID[0] ID[1]?¿Cómo puedo poner Regex.Matches en una matriz?

string value = ("{\"ID\":\"([A-Za-z0-9_., ]+)\","); 
string ID = Regex.Matches(textt, @value);` 
+1

Última vez que oí 'Matches()' devolvió una colección, no una cadena. – BoltClock

Respuesta

25

Puede hacerlo ya, ya MatchCollection tiene un int indexer que le permite acceder partidos por el índice. Esto es perfectamente válido:

MatchCollection matches = Regex.Matches(textt, @value); 
Match firstMatch = matches[0]; 

Pero si realmente quiere poner los partidos en una matriz, que puede hacer:

Match[] matches = Regex.Matches(textt, @value) 
         .Cast<Match>() 
         .ToArray(); 
+0

¿puedes publicar el equivalente vb para tu segundo fragmento de código arriba? – Smith

+1

@Smith Try: Dim matches() As Match = Regex.Matches (textt, @value) .Cast (Of Match)(). ToArray() – Crag

+0

estoy usando .net 2.0, ese molde no es compatible allí – Smith

0

otro método

string value = ("{\"ID\":\"([A-Za-z0-9_., ]+)\","); 
    MatchCollection match = Regex.Matches(textt, @value); 

    string[] ID = new string[match.Count]; 
    for (int i = 0; i < match.Length; i++) 
    { 
    ID[i] = match[i].Groups[1].Value; // (Index 1 is the first group) 
    } 
+0

Sobrecompuesto por una matriz secundaria. Ver mi respuesta – vapcguy

1

O este combo de la los últimos 2 pueden ser un poco más fáciles de tomar ... Un MatchCollection se puede usar directamente como una matriz, sin necesidad de la matriz secundaria:

string value = ("{\"ID\":\"([A-Za-z0-9_., ]+)\","); 
MatchCollection matches = Regex.Matches(textt, @value); 
for (int i = 0; i < matches.Count; i++) 
{ 
    Response.Write(matches[i].ToString()); 
} 
Cuestiones relacionadas