Skip to content
Related Articles

Related Articles

Improve Article

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

  • Last Updated : 29 Dec, 2020
Geek Week

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


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 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)
345 43 42

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up
Recommended Articles
Page :