Split string based on number of commas
<p>I have a text which is splited with commas.</p>

<p>e.g.:</p>

<pre><code>FOO( something, BOO(tmp, temp), something else)
</code></pre>

<p>It could be that <em>something else</em> contain as well a string with commas...</p>

<p>I would like to split the text inside the brakets of FOO to its elements and then pasrse the elements.</p>

<p>What i do know is that <em>FOO</em> must have two commas.</p>

<p>How could I split the contant of <em>FOO</em> to its three elements?</p>

<p><strong>Remark:</strong> <em>something else</em> could be <em>BOO(ddd, ddd)</em> or simply <em>ddd</em>. I can not assume a simple regex regel of <em>'FOO\(\w+, BOO(\w+, \w+), \w+\)'</em></p>

<p>You can do it with the <a href="https://pypi.python.org/pypi/regex" rel="nofollow">regex module</a> that supports recursion (useful to deal with nested structures):</p>

<pre><code>import regex

s = 'FOO( something, BOO(tmp, temp), something else)'

pat = regex.compile(r'''(?(DEFINE) # inside a definition group
    # you can define subpatterns to use later
    (?P&lt;elt&gt;     # define the subpattern "elt"
        [^,()]*+
        (?:
            \( (?&amp;elt) (?: , (?&amp;elt) )* \)
            [^,()]*
        )*+
    )
)
# start of the main pattern
FOO\( \s*
    (?P&lt;elt1&gt; (?&amp;elt) )  # capture group "elt1" contains the subpattern "elt"
    , \s*
    (?P&lt;elt2&gt; (?&amp;elt) )  # same here
    , \s*
    (?P&lt;elt3&gt; (?&amp;elt) )  # etc.
\)''', regex.VERSION1 | regex.VERBOSE )

m = pat.search(s)

print(m.group('elt1'))
print(m.group('elt2'))
print(m.group('elt3'))
</code></pre>

<p><a href="https://regex101.com/r/eMtX6U/1" rel="nofollow">demo</a></p>

python regex