2011-01-08 48 views
11

Birden çok Regex Eşleşmem var. Bunları bir diziye nasıl yerleştirebilirim ve her birini ayrı ayrı arayabilirim, örneğin ID[0] ID[1]? MatchCollection dizine tarafından eşleşmeleri erişim sağlayan bir int indexer beriRegex.Matches'i bir diziye nasıl yerleştirebilirim?

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

Last I 'Matches()' bir dizi değil bir koleksiyon döndürdüğünü duydum. – BoltClock

cevap

25

Sen çoktan bunu yapabilir.

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

Ama gerçekten bir diziye eşleşmeleri koymak istiyorsanız, bunu yapabilirsiniz: Bu mükemmel geçerlidir

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

ikinci kod snippet'iniz için vb eşdeğerini yukardan yayınlayabilir misiniz? – Smith

+1

@Smith Deneyin: Dim eşleşmeleri() As Match = Regex.Matches (textt, @value) .Cast (Of Match)() ToArray() – Crag

+0

.net 2.0 kullanarak, o cast desteklenmiyor – Smith

0

başka bir yöntemi

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

İçe aktarılması İkincil diziyle aşırı karmaşık. Cevabımı gör. – vapcguy

1

Veya bu combo Son 2, almak için biraz daha kolay olabilir ... Bir MatchCollection doğrudan bir dizi gibi kullanılabilir - ikincil dizi için gerek yok:

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()); 
} 
İlgili konular