I have a python function which uses a regular expression to match one (the first) floating point number in a given string and return the number.
How can I modify it (the regex) to generalize the function so that it returns instead a list with the all numbers in the string?
Here is a working demonstration:
import re
def extract_number(s,notfound='NOT_FOUND'):
regex='[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?' # matching any floating point number
m = re.search(regex,s)
if(m): val=m.group()
else: val=notfound
return val
example='bla1.23bar4.5fuzz6.7cat8'
print example
print extract_number(example)
In this example, the output is:
bla1.23bar4.5fuzz6.7cat8
1.23
The modified function which I am looking for, let’s call it extract_numbers (note the plural !), should output this:
bla1.23bar4.5fuzz6.7cat8
[1.23, 4.5, 6.7, 8]
Just use re.findall: