1

I have some (somewhat) working code to match US-based telephone numbers in the following format: ###-###-####

The problem is, my code is just hitting the else block in my code for each phone_number in my phone_numbers:

file = open("results.txt", "w")
rgxpattern = '^[0-9]{3}-[0-9]{3}-[0-9]{4}$'
regexp = re.compile(rgxpattern)

for phone_number in phone_numbers:
    phone_number = str(phone_number)
    if regexp.match(phone_number):                      
        file.write('\n')
        file.write(str(phone_number))
    else:
        file.write('BAD#')

Is something wrong with my rgxpattern above? I've tried using:

^[0-9]{3}-[0-9]{3}-[0-9]{4}$

and

^\d{3}-\d{3}-\d{4}$

Example Phone number:

 111-222-3333  
 777-444-4444  

Extract of results:

BAD#BAD#BAD#BAD#

Any thoughts or help?

CodeTalk
  • 3,571
  • 16
  • 57
  • 92
  • 3
    Show an example of the kind of phone numbers that your pattern didn't match, but you want it to. – p.s.w.g Jul 24 '14 at 15:40
  • [This answer](http://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation) from the [Stack Overflow Regular Expressions FAQ](http://stackoverflow.com/a/22944075/2736496) should help you. – aliteralmind Jul 24 '14 at 15:41
  • Please show an extract of `results.txt`. – Ben Jul 24 '14 at 15:41
  • 1
    What is `phone_numbers`? If it is a list of the lines in the file, then you will need to strip the newline character at the end of each. Did you do this? –  Jul 24 '14 at 15:42
  • [Please see this link for a lot of different regex validations for phone numbers](http://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation) – heinst Jul 24 '14 at 15:43
  • @Ben - please see the above extraction – CodeTalk Jul 24 '14 at 15:47
  • @p.s.w.g - see the examples above – CodeTalk Jul 24 '14 at 15:48

1 Answers1

6

If your "Example Phone numbers" is accurate, then there is white space before and after each phone number, this should remedy the problem:

^\s*\d{3}-\d{3}-\d{4}\s*$
Ben
  • 1,113
  • 1
  • 7
  • 14