2010-02-28 203 views
11

在PHP我可以使用foreach循环,使得我能够访问例如键和值既:C#foreach循环

foreach($array as $key => $value) 

我有以下代码:

Regex regex = new Regex(pattern); 
MatchCollection mc = regex.Matches(haystack); 
for (int i = 0; i < mc.Count; i++) 
{ 
    GroupCollection gc = mc[i].Groups; 
    Dictionary<string, string> match = new Dictionary<string, string>(); 
    for (int j = 0; j < gc.Count; j++) 
    { 
     //here 
    } 
    this.matches.Add(i, match); 
} 

//here我想要match.add(key, value)但我不知道如何从GroupCollection中获取密钥,在这种情况下应该是捕获组的名称。我知道gc["goupName"].Value包含匹配的值。

+0

哪个是关键,哪个是价值? – kennytm 2010-02-28 10:09:23

回答

10

在.NET中,组名称可对Regex实例:

// outside all of the loops 
string[] groupNames = regex.GetGroupNames(); 

然后可以遍历在此基础上:

Dictionary<string, string> match = new Dictionary<string, string>(); 
foreach(string groupName in groupNames) { 
    match.Add(groupName, gc[groupName].Value); 
} 

或者,如果你想使用LINQ :

var match = groupNames.ToDictionary(
      groupName => groupName, groupName => gc[groupName].Value); 
3

您不能直接访问组名,hou必须在正则表达式实例(see doc)上使用GroupNameFromNumber

Regex regex = new Regex(pattern); 
MatchCollection mc = regex.Matches(haystack); 
for (int i = 0; i < mc.Count; i++) 
{ 
    GroupCollection gc = mc[i].Groups; 
    Dictionary<string, string> match = new Dictionary<string, string>(); 
    for (int j = 0; j < gc.Count; j++) 
    { 
     match.Add(regex.GroupNameFromNumber(j), gc[j].Value); 
    } 
    this.matches.Add(i, match); 
} 
4

在C#3中,您还可以使用LINQ执行此类收集处理。用于使用正则表达式的类只实现非泛型IEnumerable,因此您需要指定几种类型,但它仍然非常优雅。

以下代码为您提供了包含组名称作为键和匹配值作为值的词典集合。它使用Marc的建议来使用ToDictionary,除了它指定组名作为密钥(我认为认为 Marc代码使用匹配值作为键和组名作为值)。

Regex regex = new Regex(pattern); 
var q = 
    from Match mci in regex.Matches(haystack) 
    select regex.GetGroupNames().ToDictionary(
    name => name, name => mci.Groups[name].Value); 

然后,您可以将结果分配给您的this.matches

+0

@Tomas - 固定的;好点。 – 2010-02-28 10:42:56