views:

73

answers:

2

Dive into python gives an amazing little tutorial on creating a regular expression for phone numbers (http://diveintopython.org/regular_expressions/phone_numbers.html)

The final version comes out to look like:

phone_re = re.compile(r'(\d{3})\D*(\d{3})\D*(\d{4})\D*(\d*)$', re.VERBOSE)

This works fine for almost all examples I can come up with, however I found a pretty big failure that I can't seem to fix.

If a group of 3 digits comes before the phone number it works fine. IE: "500 dollars off, call 123-456-7891"

If a group of 3 digits comes after the phone number it fails. IE: "Call 123-456-7891 for a discount of up to 500"

Any ideas on a fix that would work for both examples?

+1  A: 

The (\d*)$ requires that the string you're matching against end with digit characters (the $ signifies "end of line"). Try removing the $ if you're matching against a larger string where the phone number may not be at the end of the line.

Amber
A: 
robert