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 4Input: 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) print(*array) |
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.
Recommended Posts:
- Python - Check whether a string starts and ends with the same character or not (using Regular Expression)
- Regular Expression in Python with Examples | Set 1
- Check if an URL is valid or not using Regular Expression
- Validating Roman Numerals Using Regular expression
- Remove duplicate words from Sentence using Regular Expression
- Python - Evaluate Expression given in String
- Lambda expression in Python to rearrange positive and negative numbers
- Regular Expressions in Python | Set 2 (Search, Match and Find All)
- Python | Find the Number Occurring Odd Number of Times using Lambda expression and reduce function
- Evaluate an array expression with numbers, + and -
- Python | Frequency of numbers in String
- Python | Check whether string contains only numbers or not
- Python | Extract numbers from string
- Python - Retain Numbers in String
- Python - Descending Sort String Numbers
- Python | Print all string combination from given numbers
- Python - Get summation of numbers in string list
- Python | Extract Numbers in Brackets in String
- Python | Convert Joint Float string to Numbers
- Python | Embedded Numbers Summation in String List
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

