Tuesday, January 20, 2026
HomeLanguagesFind all the numbers in a string using regular expression in Python

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

Given a string str containing numbers and alphabets, the task is to find all the numbers in str using regular expression. 

Examples:

Input: abcd11gdf15hnnn678hh4 
Output: 11 15 678 4 

Input: 1abcd133hhe0 
Output: 1 133 0

Approach: The idea is to use Python re library to extract the sub-strings from the given string which match the pattern [0-9]+. This pattern will extract all the characters which match from 0 to 9 and the + sign indicates one or more occurrence of the continuous characters. 

Below is the implementation of the above approach: 

Python3




# Python3 program to extract all the numbers from a string
import re
 
# Function to extract all the numbers from the given string
def getNumbers(str):
    array = re.findall(r'[0-9]+', str)
    return array
 
# Driver code
str = "adbv345hj43hvb42"
array = getNumbers(str)
print(*array)


Output

345 43 42

Time Complexity : O(n), where n is length of str string.

Auxiliary Space : O(n), where n is length of array.

RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32474 POSTS0 COMMENTS
Milvus
118 POSTS0 COMMENTS
Nango Kala
6847 POSTS0 COMMENTS
Nicole Veronica
11977 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12064 POSTS0 COMMENTS
Shaida Kate Naidoo
6986 POSTS0 COMMENTS
Ted Musemwa
7220 POSTS0 COMMENTS
Thapelo Manthata
6933 POSTS0 COMMENTS
Umr Jansen
6912 POSTS0 COMMENTS