2011-01-08 113 views
11

我有多个正则表达式匹配。我怎样才能把它们放入一个数组中,并且分别对它们进行调用,例如ID[0] ID[1]如何将Regex.Matches放入数组中?

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

最后我听说`Matches()`返回了一个集合,而不是一个字符串。 – BoltClock 2011-01-08 05:02:23

回答

25

你能做到这一点已经,因为MatchCollectionint indexer,让您通过索引来访问比赛。这是完全正确的:

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

但如果你真的想要把比赛放到一个数组,你可以这样做:

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

你可以发布上面的第二个代码片段的vb等价物吗? – Smith 2011-06-02 10:19:03

+1

@Smith Try:Dim matches()As Match = Regex.Matches(textt,@value).Cast(Of Match)()。ToArray() – Crag 2011-06-03 00:00:28

0

另一种方法

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) 
    } 
1

或者这个组合的最后2个可能会容易一些... MatchCollection可以像直接使用数组一样使用 - 不需要辅助数组:

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