Extract weight of an item from its description using regex in python
<p>I have a list of product descriptions. for example:</p>

<pre><code> items = ['avuhovi Grillikaapeli 320g','Savuhovi Kisamakkara 320g',
'Savuhovi Raivo 250g', 'AitoMaku str.garl.sal.dres.330ml', 'Rydbergs
 225ml Hollandaise sauce']
</code></pre>

<p>I want to extract the weights that is, 320g, 320g, 250ml, 330ml. I know we can use regex for this but do not know how to buil regex to extract that. You can see that weights are sometimes in the middle of the description and sometimes having dot(.) as separator rather than space. So, I am confused how to extract.</p>

<p>Thanks for help in advance :)</p>

<p>He is one solution that may work (using <code>search</code> and <code>group</code> suggested by Wiktor):</p>

<pre><code>&gt;&gt;&gt; for t in items :
...   re.search(r'([0-9]+(g|ml))', t).group(1)
... 
'320g'
'320g'
'250g'
'330ml'
'225ml'
</code></pre>

<p>Indeed a better solution (thanks Wiktor) would be to test if there is a match :</p>

<pre><code>&gt;&gt;&gt; res = []
&gt;&gt;&gt; for t in items :
...   m = re.search(r'(\d+(g|ml))', t)
...   if m:
...     res.append(m.group(1))

print res 
</code></pre>

python regex