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>Assuming that you need a list of elements inside <code>FOO</code>, so pre-processing it first</p>

<pre><code>&gt;&gt;&gt; s = 'FOO( something, BOO(tmp, temp), something else)'
&gt;&gt;&gt; s
'FOO( something, BOO(tmp, temp), something else)'
&gt;&gt;&gt; s = re.sub(r'^[^(]+\(|\)\s*$','',s)
&gt;&gt;&gt; s
' something, BOO(tmp, temp), something else'
</code></pre>

<p>Using <a href="https://pypi.python.org/pypi/regex" rel="nofollow">regex</a> module:</p>

<pre><code>&gt;&gt;&gt; regex.split(r'[^,(]+\([^)]+\)(*SKIP)(?!)|,', s)
[' something', ' BOO(tmp, temp)', ' something else']
</code></pre>

<ul>
<li><code>[^,(]+\([^)]+\)(*SKIP)(?!)</code> to skip the pattern <code>[^,(]+\([^)]+\)</code></li>
<li><code>|,</code> alternate pattern to actually split the input string, in this case it is <code>,</code></li>
</ul>

<p><br>
another example:</p>

<pre><code>&gt;&gt;&gt; t = 'd(s,sad,e),g(3,2),c(d)'
&gt;&gt;&gt; regex.split(r'[^,(]+\([^)]+\)(*SKIP)(?!)|,', t)
['d(s,sad,e)', 'g(3,2)', 'c(d)']
</code></pre>

python regex