Pattern matching python - return multiple items from input in one go
<p>Input: </p>

<pre><code>A-&gt;(B, 1), (C, 2), (AKSDFSDF, 1231231) ...
</code></pre>

<p>Expected output:</p>

<pre><code>[('A', 1, 2, 1231231)]
</code></pre>

<p>Cannot seem to get it to work. My code:</p>

<pre><code>import re

pattern = r"([a-zA-z]+)-&gt;(.*)"
r = re.compile(pattern)

print r.findall("A-&gt;(B, 1), (C, 2), (AKSDFSDF, 1231231)")
&gt;&gt;&gt; [('A', '(B, 1), (C, 2), (AKSDFSDF, 1231231)')]
</code></pre>

<p>That's close enough, but surely it's possible to extract exactly what I want?</p>

<p>I would have though this could work, but it doesnt:</p>

<pre><code>pattern = r"([a-zA-z]+)-&gt;([\([a-zA-Z]+,([0-9]+)\)]*)"
</code></pre>

<p>That throws empty output (ie. <code>[]</code>), while this:</p>

<pre><code>pattern = r"([a-zA-z]+)-&gt;((\([a-zA-Z]+,([0-9]+)\))*)"
&gt;&gt;&gt; [('A', '', '', '')]
</code></pre>

<p>Any idea?</p>

<p>You can use a <em>positive lookahead assertion</em> to pick words starting with a word boundary <code>\b</code> and followed by <code>-</code> or <code>)</code>:</p>

<pre><code>import re

s = 'A-&gt;(B, 1), (C, 2), (AKSDFSDF, 1231231)'
pattern = re.compile(r'\b\w+(?=-|\))')
print pattern.findall(s)
#['A', '1', '2', '1231231']
</code></pre>

<p>Try it out: <a href="https://repl.it/DqSe/0" rel="nofollow">https://repl.it/DqSe/0</a></p>

python regex pattern-matching