# Phone number extraction with regular expressions

I've been working on my own phone number extraction snippet of Regex code and I'd appreciate your feedback on it. I've tried to make it match as many different types of numbers as I knew existed in the US. (I'm sure there's some I missed.) Is there anything I can do to improve this?

(?:\+?(\d{1})?-?$$?(\d{3})$$?[\s-\.]?)?(\d{3})[\s-\.]?(\d{4})[\s-\.]?

Here's a picture of it in action:

You can test the code out here.

Also for this interested, here is the flow of the "logic":

(Made from pasting the code into here)

• What flavor of regex is this? What language is it used in? Jul 21 '15 at 15:57
• It produces the same results in PHP and Python Jul 21 '15 at 16:09
• One minor bug is that it doesn't require the area code parentheses to be matched. Also, adding named capture groups might help you with any further processing. Jul 21 '15 at 16:35
• @jonrsharpe Sometimes parenthesis aren't required when entering a phone number so I didn't require them. Also I didn't know about named catpure groups. Thanks for the heads up :) Jul 21 '15 at 16:45
• I know that - I mean that it matches e.g. '1-800)-123-4567', which may be undesirable Jul 21 '15 at 16:47

\D?(\d{0,3}?)\D{0,2}(\d{3})?\D{0,2}(\d{3})\D?(\d{4})$I tried to take out some of the conditional and capturing groups to clear it up. So we can split this into four part: 1. \D?(\d{0,3}?) Is there anything that isn't a number? it's probably a + or something so we'll make sure not to capture that. Then we look for a country code. You had only a check for a single digit country code, and if that's what you want, fine. However, know that some nations have codes more than one character in length. 2. \D{0,2}(\d{3})? Is there a dash or a parenthesis? Or both? If so, count those out. Is there an area code? If so, capture it. 3. \D{0,2}(\d{3}) Same as the previous section, except we're expecting to find those 3 digits, as they're necessary. 4. \D?(\d{4})$