0

Is there a way to extract unique captured groups matching a regex pattern in c# .net ? I need to a have list uniqueSiteElementKeys3 with 2 elements, SiteElements[10] and SiteElements[11]

string lineOfKeys = "SiteElements[10].TempateElementId,SiteElements[10].TemplateElementValue,SiteElements[11].TempateElementId,SiteElements[11].TemplateElementValue";
string pattern3 = @"(?<SiteElements>^\b(SiteElements\[[0-9]+\]))";                        
List<string> uniqueSiteElementKeys3 = new List<string>();
foreach (Match match in Regex.Matches(lineOfKeys, pattern3))
{
  if (uniqueSiteElementKeys3.Contains(match.Groups[1].Value) == false)
  {
     uniqueSiteElementKeys3.Add(match.Groups[1].Value);
  }
}
4

1 回答 1

0

只需为此使用普通的旧 LINQ:

var uniqueSiteElementKeys3 = Regex.Matches(lineOfKeys, @"\bSiteElements\[[0-9]+\]")
                                  .Cast<Match>()
                                  .Select(match => match.Value)
                                  .Distinct()
                                  .ToList();

演示

于 2014-11-04T22:15:00.220 回答