Home > Enterprise >  Match an expression as a list
Match an expression as a list

Time:07-20

I have a string that I am trying to create a regular expression to match the assignment name "People" and its list of people

People = "Alice", "Bob", "Charlie", "David", "Erica", "Fred";

Conditions:

  • The expression name "People" must be returned
  • Any number of names must be returned separately (in groups)

I have looked to see if I could find something similar Match list of words without the list of chars around But I am not sure if this is the correct thing, or how to apply it.

The Regex expression I have tried

( \"([A-Z0-9] )\",?)

This seems to match all of the individual names, however I am not sure how I can retrieve "People" in a separate group.

Is this a case for lookaround expressions in Regex? If so, how can it be implemented?

CodePudding user response:

You could make the pattern even more specific, but in this case you might use the CapturesCollection in C# by using a repeated capture group:

\b(?<name>[A-Za-z0-9] )\s*=\s*(?:\"(?<people>[A-Za-z0-9] )\",?\s*) ;

Regex demo | C# demo

Example to get the values:

string pattern = @"\b(?<name>[A-Za-z0-9] )\s*=\s*(?:\""(?<people>[A-Za-z0-9] )\"",?\s*) ;";
string input = @"People = ""Alice"", ""Bob"", ""Charlie"", ""David"", ""Erica"", ""Fred"";";
Match match = Regex.Match(input, pattern);
var name = match.Groups["name"].Value;
var strings = match.Groups["people"].Captures.Select(c => c.Value);

Console.WriteLine(name);

foreach (String s in strings)
{
    Console.WriteLine("-> "  s);
}

Output

People
-> Alice
-> Bob
-> Charlie
-> David
-> Erica
-> Fred
  • Related