2011-01-08 16 views
11

Ho più corrispondenze Regex. Come posso inserirli in un array e chiamarli singolarmente, ad esempio ID[0] ID[1]?Come posso inserire Regex.Match in una matrice?

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

Infine ho sentito che 'Matches()' ha restituito una raccolta, non una stringa. – BoltClock

risposta

25

Si può fare già, dal momento che ha un MatchCollectionint indexer che consente di accedere partite in base all'indice. Ciò è perfettamente valido:

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

Ma se si vuole veramente mettere le partite in un array, si può fare:

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

puoi pubblicare l'equivalente vb per il tuo secondo snippet di codice sopra? – Smith

+1

@Smith Prova: Dim corrispondenze() Come corrispondenza = Regex.Match (textt, @value) .Cast (Of Match)(). ToArray() – Crag

+0

am utilizzando .net 2.0, il cast non è supportato lì – Smith

0

un altro metodo

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

Complicato dall'array secondario. Vedi la mia risposta. – vapcguy

1

O questo combo del l'ultimo 2 potrebbe essere un po 'più facile da accettare ... Un MatchCollection può essere usato direttamente come un array: non c'è bisogno dell'array secondario:

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()); 
} 
Problemi correlati