0

My question was marked as a duplicate so I've made a couple edits. As I said, I was able to find many similar questions when I searched but none were quite what I needed. I am not validating a string where the only thing present will be the phone number (this seems to be what most of the other questions are addressing). Rather, I am attempting to pull out all phone numbers (which will then be manually checked by the user) from a larger block of text. The problem I am having is that my regular expression is matching zip codes with extensions (ex: 45202-4787), and I am not sure how to alter my regex to avoid that. If this truly is a duplicate question then I apologize for not being able to find the existing one that deals with my issue.

My specifications for phone number format are:

1) -, ., and space as delimiters (and in any combination)

2) area code may appear with or without parentheses

A few examples:

(xxx) xxx-xxxx
(xxx) xxx.xxxx
xxx-xxx-xxxx
xxx xxx-xxxx
xxxxxxxxxxx

I am using Anirudh's regex from the comments:

(\(?\d{3}\)?)?[. -]?\d{3}[. -]?\d{4}

Again, my problem is that this regex matches zip codes with extensions (ex: 45202-4787).

I would be grateful for any help, as I'm very new to using regular expressions. Thanks!

3
  • There are a few suggestions in the second answer here: stackoverflow.com/questions/123559/…
    – o_weisman
    Dec 8, 2013 at 12:27
  • Your regex is correct..I guess it's the problem with your text..Could you show us that text..Though your regex should be (\(?\d{3}\)?)?[. -]?\d{3}[. -]?\d{4}
    – Anirudha
    Dec 8, 2013 at 12:35
  • I think I found the issue, but I'm not sure how to fix it. My regex is matching the zipcode in my text block (45202-4787). I thought it was part of a phone number but I was wrong.
    – JChurch
    Dec 8, 2013 at 13:02

1 Answer 1

0

This should do it:

 ^(\([0-9]{3}\)|[0-9]{3})[ -\.]?[0-9]{3}[ -\.]?[0-9]{4}$

Not the answer you're looking for? Browse other questions tagged or ask your own question.