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>You can use your <code>import\s+(?:([a-zA-Z0-9=]+),*\s*)*</code> regex (I just fixed the <code>0-9</code> range to match any digit and included <code>=</code> to the end) and access the Group 1 capture stack using <a href="https://pypi.python.org/pypi/regex" rel="nofollow">PyPi regex module</a>:</p>

<pre><code>&gt;&gt;&gt; import regex
&gt;&gt;&gt; s = 'import pandas, os, sys'
&gt;&gt;&gt; rx = regex.compile(r'^import\s+(?:([a-zA-Z0-9=]+),*\s*)*$')
&gt;&gt;&gt; print([x.captures(1) for x in rx.finditer(s)])
[['pandas', 'os', 'sys']]
</code></pre>

python regex