python regex to split list entry's name into list name and index
<p>How can I use regular expressions to parse <code>&lt;listname&gt;[#]</code> into <code>[listname, #]</code>?</p>

<p>Here's what I've tried:</p>

<pre><code>&gt; s = 'li[10]'
&gt; re.split(s,r'[%d]')
['[%d]']
&gt; re.findall(s,r'[%d]')
[]
&gt; s.split(r'[%d]')
['li[0]']
</code></pre>

<p>the desired output is <code>li</code> and <code>10</code></p>

<p>I can also suggest a more restrictive pattern to use with <code>re.findall</code>:</p>

<pre><code>re.findall(r'(\w+)\[(\d+)]', s)
</code></pre>

<p>See the <a href="http://ideone.com/a53Sh9" rel="nofollow">Python demo</a></p>

<p>Or a variation with <code>zip</code>:</p>

<pre><code>import re
s = 'li[10] li[11]'
names, ids = zip(*re.findall(r"(\w+)\[(\d+)]", s))
print(names)
print(ids)
</code></pre>

<p>See <a href="http://ideone.com/KICcfk" rel="nofollow">another Python demo</a></p>

<p><em>Details</em>:</p>

<ul>
<li><code>(\w+)</code>  - Group 1 capturing one or more letters, digits or underscores</li>
<li><code>\[</code> - a <code>[</code> literal symbol </li>
<li><code>(\d+)</code>  - Group 2 capturing 1 or more digits</li>
<li><code>]</code> - a closing literal <code>]</code> symbol</li>
</ul>

python regex