Regex capturing group within non-capturing group
<p>In Python, how do you capture a group within a non-capturing group? Put in another way, how do you repeat a non-capturing sub-pattern that contains a capturing group?</p>

<p>An example of this would be to capture all of the package names on an import string. E.g. the string:</p>

<blockquote>
  <p>import pandas, os, sys</p>
</blockquote>

<p>Would return 'pandas', 'os', and 'sys'. The following pattern captures the first package and gets up to the second package:</p>

<pre><code>import\s+([a-zA-Z0=9]*),*\s*
</code></pre>

<p>From here, I would like to repeat the sub-pattern that captures the group and matches the following characters, i.e.<code>([a-zA-Z0=9]*),*\s*</code>. When I surround this sub-pattern with a non-capturing group and repeat it:</p>

<pre><code>import\s+(?:([a-zA-Z0=9]*),*\s*)*
</code></pre>

<p>It no longer captures the group inside.</p>

<p>Your question is phrased strictly about regex, but if you're willing to use a <a href="https://en.wikipedia.org/wiki/Recursive_descent_parser" rel="nofollow">recursive descent parser</a> (e.g., <a href="http://pyparsing.wikispaces.com/" rel="nofollow"><code>pyparsing</code></a>), many things that require expertise in regex, become very simple.</p>

<p>E.g., here what you're asking becomes</p>

<pre><code>from pyparsing import *

p = Suppress(Literal('import')) + commaSeparatedList

&gt;&gt;&gt; p.parseString('import pandas, os, sys').asList()
['pandas', 'os', 'sys']

&gt;&gt;&gt; p.parseString('import                    pandas,             os').asList()
['pandas', 'os']
</code></pre>

<hr>

<p>It might be a matter of personal taste, but to me, </p>

<pre><code>Suppress(Literal('import')) + commaSeparatedList
</code></pre>

<p>is also more intuitive than a regex.</p>

python regex