Mobile numbers from a file
Write a Python program to get all 10-digit mobile numbers from a file.
['9876543210', '9123456780']
Approach
re.findall(r"\b\d{10}\b", text).
Solution
import re with open("contacts.txt", "w") as f: f.write("Asha 9876543210\nRavi 12345\nMeena 9123456780 and 99887766554\n") with open("contacts.txt") as f: print(re.findall(r"\b\d{10}\b", f.read()))['9876543210', '9123456780']
Line by line
The 11-digit number does not match because \b requires the digits to end there.
Learn the concept
New to this topic? Read the lesson, then come back.