簡體   English   中英

如何獲得相同的正則表達式匹配項?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM