Python RegEx - Find numbers of Specific Length in String


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.

Examples

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.

Python Program

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)

Output

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.

  1. re.findall('[0-9]+', str) returns all the words that are numbers.
  2. The function filterNumber(n) returns true if the length of the number n equals length that we specified N.
  3. Filter the list returned in step 1 with the function defined in step 2.
  4. The filter in step 3 returns the list containing the numbers that are of the length specified.

Summary

In this tutorial of Python Examples, we learned how to get the list of numbers with a specific length, using Python Regular Expression.