2016-11-17 58 views
0

如果我想在裏面找使用正則表達式在字符串中括號內的所有文字,我想有這樣的事情:如何獲得相同的正則表達式匹配組合?

string text = "[the] [quick] brown [fox] jumps over [the] lazy dog"; 
Regex regex = new Regex(@"\[([^]]+)\]"); 
MatchCollection matches = regex.Matches(text); 

foreach (Match match in matches) 
{ 
    ... // Here is my problem! 
} 

我不知道如何繼續我的代碼從這裏,如果我只是遍歷所有匹配,我會得到"the","quick","fox""the",我期待得到兩個the分組在相同的Match.Group,只是在不同的指標。

我真的是讓兩個"the"以這樣的方式,我可以找到所有相同的字和它們的索引中出現的分組。

我希望的API會給我這樣的事情:

foreach (Match match in matches) 
{ 
    for (int i = 1; i < match.Groups.Count; i++) 
    { 
     StartIndexesList.Add(match.Groups[i].Index); 
    } 
} 

如果每個match.Group將舉行到的一些發現令牌中的文字相同的發生的基準,所以我預計這個代碼將增加所有the文本索引一次引用列表,但它不是,它只是爲每個單獨的事件添加,而不是一次全部引用。

如何在沒有後處理所有令牌的情況下實現此目的,以查看是否有重複的令牌?

回答

1

這是你在找什麼?

string text = "[the] [quick] brown [fox] jumps over [the] lazy dog"; 
Regex regex = new Regex(@"\[([^]]+)\]"); 
MatchCollection matches = regex.Matches(text); 

foreach (IGrouping<string, Match> group in matches.Cast<Match>().GroupBy(_ => _.Value)) 
{ 
    Console.WriteLine(group.Key); // This will print '[the]' 

    foreach (Match match in group) // It will iterate through all matches of '[the]' 
    { 
     // do your stuff 
    } 
} 
+0

This Works,thanks!我期待着來自'Regex' API本身的東西,但我猜想畢竟沒有一個。 – mFeinstein

相關問題