M Hassan M Hassan - 4 months ago 8
Python Question

How to get a number from a string with regex

I have a string which have following pattern. String will always remain same. Just numbers will be different

Showing Results (1 – 15 of 96,831)


I want to extract
96,831
from that string. I want to do this with regex. What can be regex for that? I have tried a way where I am using two regex but still not getting required number.

"Showing Results (1 – 15 of 96,831)".replace(/[a-zA-Z\(\)]+/g, '').replace(/(\d+ – \d+)/g, '')


Its output is as follow. This output contains spaces which are not required.

" 96,831"


I want a way to do this in python. Can anyone help me?

Answer

This is clear case where you should avoid regex as it just needs simple strip and split, like so:

>>> s = 'Showing Results (1 – 15 of 96,831)'
>>> num = s.split()[-1]
'96,831)'
>>> num.strip(')')
'96,831'

Or, using str.rstrip:

>>> num = s.rsplit(maxsplit=1)[-1]
>>> num
'96,831)'
>>> num.strip(')')
'96,831'

But if you insist on using regex, then this pattern might do the job for you:

>>> import re
>>> nums = re.findall(r'\d+,?\d*', s)
['1 ', '15 ', '96,831']
>>> nums[-1]
'96,831'

And if you want to convert it to float don't forget to replace , with .:

>>> num
'96,831'
>>> 
>>> num = num.replace(',','.')
>>> num
'96.831'
>>> float(num)
96.831