如何获得相同的正则表达式匹配组合?
问题描述:
如果我想在里面找使用正则表达式在字符串中括号内的所有文字,我想有这样的事情:如何获得相同的正则表达式匹配组合?
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
文本索引一次引用列表,但它不是,它只是为每个单独的事件添加,而不是一次全部引用。
如何在没有后处理所有令牌的情况下实现此目的,以查看是否有重复的令牌?
答
这是你在找什么?
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
}
}
This Works,thanks!我期待着来自'Regex' API本身的东西,但我猜想毕竟没有一个。 – mFeinstein