Tom
Tom

Reputation: 781

regular expression us phone number

I have a regular expression that matches the following numbers.

8702431273

973-882-9444 ext 6114

1-223-332-2232

However it does not match.

(+1) 623-975-5296

605-367-7321

How can I modify this to also accept these.

^(?:1(?:[. -])?)?(?:\((?=\d{3}\)))?([2-9]\d{2})(?:(?<=\(\d{3})\))? ?(?:(?<=\d{3})[.-])?([2-9]\d{2})[. -]?(\d{4})(?: (?i:ext)\.? ?(\d{1,5}))?$

Upvotes: 0

Views: 296

Answers (2)

Birei
Birei

Reputation: 36282

I would incorporate next part to your regexp to match those other telephones:

(?:\(\+\d\)\s)

It means the plus sign with a digit. Adapt it if can be more digits inside parenthesis or more space after it. Final regexp could be like this.

^(?:(?:1(?:[. -])?)?(?:\((?=\d{3}\)))?|(?:\(\+\d\)\s))?([2-9]\d{2})(?:^(?<=\(\d{3})\))? ?(?:(?<=\d{3})[.-])?([2-9]\d{2})[. -]?(\d{4})(?: (?i:ext)\.? ?(\d{1,5}))?$

I divide in lines the part I've changed to adapt new telephone numbers:

^
  (?:
    (?:1(?:[. -])?)?
    (?:\((?=\d{3}\)))?
      |
    (?:\(\+\d\)\s)
   )?
([2-9]\d{2})(?:^(?<=\(\d{3})\))? ?(?:(?<=\d{3})[.-])?([2-9]\d{2})[. -]?(\d{4})(?: (?i:ext)\.? ?(\d{1,5}))?$

In my test it works with the five telephones of your post.

Upvotes: 1

Justin Morgan
Justin Morgan

Reputation: 30700

It looks to me like you can simply replace this part at the beginning:

^(?:1(?:[. -])?)?

with this:

^(?:\(?\+?1\)?(?:[. -])?)?

Or if you want to be strict about the parentheses matching:

^(?:(?:\((?=.?1\)))?\+?1\)?(?:[. -])?)?

Upvotes: 1

Related Questions