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><a href="https://regex101.com/r/gy5YTp/4" rel="nofollow">https://regex101.com/r/gy5YTp/4</a></p>

<p>Match any digit with <code>\d+</code> then create a matching but non selecting group with <code>(?:ml|g)</code> this will match ml or g. </p>

<pre><code>import re

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

groupedWeights = [re.findall('(\d+(?:ml|g))', i) for i in items]
flattenedWeights = [y for x in groupedWeights for y in x]

print(flattenedWeights)
</code></pre>

<p>The match that we make returns a list of lists of weights found so we need to flatten that with <code>[y for x in groupedWeights for y in x]</code></p>

<p>That is if you ever have more than one weight in an element. Otherwise we can take the first element of each list like this.</p>

<pre><code>weights = [re.findall('(\d+(?:ml|g))', i)[0] for i in items]
</code></pre>

python regex