Python RegEx – Extract or Find All the Numbers in a String

Python Regex – Get List of all Numbers from String

To get the list of all numbers in a String, use the regular expression ‘[0-9]+’ with re.findall() method. [0-9] represents a regular expression to match a single digit in the string. [0-9]+ represents continuous digit sequences of any length.

numbers = re.findall('[0-9]+', str)

where str is the string in which we need to find the numbers. re.findall() returns list of strings that are matched with the regular expression.

Example 1: Get the list of all numbers in a String

In the following example, we will take a string, We live at 9-162 Malibeu. My phone number is 666688888., and find all the numbers, ['9', '162', '666688888'], present in the string.

Python Program

import re

str = 'We live at 9-162 Malibeu. My phone number is 666688888.'
#search using regex
x = re.findall('[0-9]+', str)
print(x)
Run

Output

['9', '162', '666688888']

Example 2: Get the list of all continuous digits in a String

In the following example, we will take a string, We four guys, live at 2nd street of Malibeu. I had a cash of $248 in my pocket. I got a ticket with serial number 88796451-52., and find all the numbers, ['2', '248', '88796451', '52'], present in the string.

Python Program

import re

str = 'We four guys, live at 2nd street of Malibeu. I had a cash of $248 in my pocket. I got a ticket with serial number 88796451-52.'
#search using regex
x = re.findall('[0-9]+', str)
print(x)
Run

Output

['2', '248', '88796451', '52']

Summary

In this tutorial of Python Examples, we learned how to get all the numbers form a string as a list, using Python Regular Expressions, with the help of example programs.