Python RegEx – Find numbers of Specific Length in String
To find numbers of specific length, N, is a string, use the regular expression [0-9]+ to find number strings of any length. [0-9] matches a single digit. After you find all the items, filter them with the length specified.
Example 1: Find numbers of specific length in a string
In the following example, we take a string, and find all the 3 digit numbers in that string.
import re str = 'We four guys, live at 2nd street of Malibeu 521. 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('All Numbers\n',x) #digits of length N N=3 def filterNumber(n): if(len(n)==N): return True else: return False #filter the list finalx = list(filter(filterNumber, x)) print('Final List\n',finalx)
All Numbers ['2', '521', '248', '88796451', '52'] Final List ['521', '248']
What have we done here?
Following is the explanation to the notable program statements in the above example.
re.findall('[0-9]+', str)returns all the words that are numbers.
- The function
filterNumber(n)returns true if the length of the number
nequals length that we specified
- Filter the list returned in step 1 with the function defined in step 2.
- The filter in step 3 returns the list containing the numbers that are of the length specified.
In this tutorial of Python Examples, we learned how to get the list of numbers with a specific length, using Python Regular Expression.
- How to Get Number of Axes in Pandas DataFrame?
- Python – Factorial of a Number
- Python String – Find the number of overlapping occurrences of a substring
- Python – Sum of First N Natural Numbers
- Python – Check if Number is Armstrong
- How to Get Number of Elements in Pandas DataFrame?
- Python Complex Number – Initialize, Access
- Python – Smallest of Three Numbers
- Python Program to Add Two Numbers
- Python – Sum of Two Numbers