Assistance with Python regex
<p>I have the following strings.</p>

<p>Example:</p>

<ul>
<li>12 CG GRB</li>
<li>6GRC 11.2 MK</li>
<li>2 GR 1.75LRG</li>
</ul>

<p>And I would like to break them to the following group</p>

<ul>
<li>[12,CG] [GRB]</li>
<li>[6,GRC] [11.2,MK]</li>
<li>[2,GR] [1.75,LRG]</li>
</ul>

<p>I'm using this regex - (\d+.?\d*).*?([A-Z]+) but with it, I'm unable to capture the first example correctly. Instead of [12,CG] [GRB], i get [12,CG].</p>

<p>Any help will be much appreciated.</p>

<pre><code>import re
p = re.compile(ur'(\d+\.?\d*).*?([A-Z]+)')
test_str = u"12 CG GRB"

re.findall(p, test_str)
</code></pre>

<p>You may replace the <code>.*?</code> with a <code>\s*</code> to match zero or more whitespasces, and make the first capture group optional:</p>

<pre><code>(\d*\.?\d+)?\s*([A-Z]+)
           ^^^^
</code></pre>

<p>See the <a href="https://regex101.com/r/tK3tL1/1" rel="nofollow">regex demo</a>.</p>

<p>Note I also modified the number matching subpattern to <code>\d*\.?\d+</code> to also mathc numbers like <code>.56</code>. You may keep your own pattern for that.</p>

<p><em>Pattern details</em>:</p>

<ul>
<li><code>(\d*\.?\d+)?</code> - Optional group 1 capturing

<ul>
<li><code>\d*</code> - zero or more digits</li>
<li><code>\.?</code> - an optional dot</li>
<li><code>\d+</code> - 1 or more digits</li>
</ul></li>
<li><code>\s*</code> - zero or more whitespaces</li>
<li><code>([A-Z]+)</code> - Group 2 capturing one or more uppercase ASCII letters.</li>
</ul>

<p>To get the capture group contents as a list of tuples, use a <code>re.findall</code> (<a href="http://ideone.com/NVwFPN" rel="nofollow">demo</a>):</p>

<pre><code>import re
p = re.compile(r'(\d*\.?\d+)?\s*([A-Z]+)')
s = "12 CG GRB\n6GRC 11.2 MK\n2 GR 1.75LRG"
print(p.findall(s))
</code></pre>

python regex