[英]How to get same Regex matches combined?
如果我想使用正則表達式查找字符串中括號內的所有文本,則將具有以下內容:
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
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.