CodeTalk
CodeTalk

Reputation: 3667

Regex to Match US Telephone Numbers

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?

Upvotes: 1

Views: 2910

Answers (1)

Ben
Ben

Reputation: 1143

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*$

Upvotes: 6

Related Questions