netrate
netrate

Reputation: 443

How to look for phone numbers in a string of text

Here is what I have so far:

import re
text = "If you want to call me, my old number was 905-343-2112 and it has 
been changed to 289-544-2345"
phone = re.findall(r'((\d{3})-(\d{3})-(\d{4}))', text)
for call in phone:
    print (call[0])

I am guessing my regular expression for finding the phone number isnt great because if I take out the square brackets when printing call, it seems to give me the whole number and then it breaks down each set of numbers. How could I polish this code

Upvotes: 3

Views: 2967

Answers (2)

Johnny Metz
Johnny Metz

Reputation: 5995

You're close but you don't need the parentheses in the pattern:

phone = re.findall(r'\d{3}-\d{3}-\d{4}', text)
print(phone)
# ['905-343-2112', '289-544-2345']

Upvotes: 3

iBug
iBug

Reputation: 37287

Use non-capturing group for segments of the phone number:

phone = re.findall(r'((?:\d{3})-(?:\d{3})-(?:\d{4}))', text)
                       ^^        ^^        ^^

Or better yet, just drop the parentheses

phone = re.findall(r'\d{3}-\d{3}-\d{4}', text)

Upvotes: 8

Related Questions