2

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

netrate
  • 423
  • 2
  • 8
  • 14
  • If you just want the entire phone number, and not the individual segments of it, then get rid of all those parentheses in the regex - they are defining capturing groups that you don't need. – jasonharper Feb 19 '18 at 04:58
  • Possible duplicate of [A comprehensive regex for phone number validation](https://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation) – ndmeiri Feb 19 '18 at 05:34

2 Answers2

7

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)
iBug
  • 35,554
  • 7
  • 89
  • 134
3

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']
Johnny Metz
  • 5,977
  • 18
  • 82
  • 146