How to split a nested comma separated list using Regex in C#



This question already has an answer here:

1 Answer: 

In .Net you can use balancing groups to capture nested structures. This is probably more complicated than the code you already have though:

    (?<Open>\()     # Increase stack depth when matching (
    (?<-Open>\))    # Decrease stack depth when matching )
    [^(),]          # Match any other character
    (?(Open),|(?!)) # Allow commas only while inside parentheses.
(?(Open)(?!))  # Ensure we have no extra open parentheses.

Live example on Regex Storm

A simpler (yet uglier) approach that works in all regex flavors is to limit the levels of nesting you support. For example:

Basically we're adding another (?:[^()]|\([^()]*\))* for each new level we want to match.