Search code examples
.netregexcapturing-group

Regex: how to extract unique groups matching a pattern


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);
  }
}

Solution

  • Just use plain old LINQ for that:

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

    Demo