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);
  }
}
Ntn
  • 3
  • 3

1 Answers1

0

Just use plain old LINQ for that:

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

Demo

Lucas Trzesniewski
  • 50,214
  • 11
  • 107
  • 158
  • Thank you for a quick response, Lucas. Will try and let you know. – Ntn Nov 04 '14 at 22:26
  • Yeah, i was wrong. Was still using the old pattern. Your solution worked. I beat my brains out for a couple of hours to find a solution, thank you Lucas. – Ntn Nov 04 '14 at 22:41