Find all the numbers in a string using regular expression in Python


Extracting only the numbers from a text is a very common requirement in python data analytics. It is done easily using the python regular expression library. This library helps us define the patterns for digits which can be extracted as substrings.

Examples

In the below example we use the function findall() from the re module. The parameters to these function are the pattern which we want to extract and the string from which we want to extract. Please note with below example we get only the digits and not the decimal points or the negative signs.

import re
str=input("Enter a String with numbers: \n")
#Create a list to hold the numbers
num_list = re.findall(r'\d+', str)
print(num_list)

Output

Running the above code gives us the following result −

Enter a String with numbers:
Go to 13.8 miles and then -4.112 miles.
['13', '8', '4', '112']

Capturing the Decimal point and Signs

We can expand the search pattern to include the decimal points and the negative or positive signs also in the search result.

Examples

import re
str=input("Enter a String with numbers: \n")
#Create a list to hold the numbers
num_list=re.findall(r'[-+]?[.]?[\d]+',str)
print(num_list)

Output

Running the above code gives us the following result −

Enter a String with numbers:
Go to 13.8 miles and then -4.112 miles.
['13', '.8', '-4', '.112']
raja
Published on 07-Aug-2019 08:42:28
Advertisements