Search code examples
c#regexpattern-matchingregex-groupmultiple-matches

Howto get groups by repeated pattern with qantizer in regular expression


I have the following string:

(a,b,c,d,e)

I want to get out all comma separated values by a regular expression.

If I put away the brackets

a,b,c,d,e

and use the following regular expression:

([^,]),?

I get out one match as well as one group for each comma separated value.

But if I want to do with concluding brackets using the regular expression:

\((([^,]),?)+\)

I still get only one match and one group. The group contains only the last comma separated value.

I tried also with group captures like:

(?:....)
(...?)
(...)?

but I cannot get out the comma separated values by regular expression groups.

How can I do this, when the comma separated values are enclosed in brackets?


Solution

  • I found it out. Using C# you can use the property Captures in the Match Collection.

    Using Regex:

    \((([^,]),?)+\)
    

    Do:

            string text = "(a,b,c,d,e)";
            Regex rgx = new Regex("\\((([^,]),?)+\\)");
            MatchCollection matches = rgx.Matches(text);
    

    Then you have 1 item with the following 3 groups in the matchcollection:

    [0]: \((([^,]),?)+\) => (a,b,c,d,e)
    [1]: ([^,]),?+ => value and optional comma, eg. a, or b, or e
    [2]: [^,] => value only, eg. a or b or ...
    

    The list captures within the group stores each extracted value by quantizer. So use group [2] and captures to get out all the values.

    So the solution is:

            string text = "(a,b,c,d,e)";
            Regex rgx = new Regex("\\((([^,]),?)+\\)");
            MatchCollection matches = rgx.Matches(text);
    
            //now get out the captured calues
            CaptureCollection captures = matches[0].Groups[2].Captures;
    
            //and extract them to list
            List<string> values = new List<string>();
            foreach (Capture capture in captures)
            {
                values.Add(capture.Value);
            }