user181218
user181218

Reputation: 1695

Regular expression to match US phone numbers

The regular expression ^((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}$ matches strings of the form XXX-XXX-XXXX and XXX-XXXX (am I missing out something?).

It doesn't, however, match (XXX) XXX-XXXX and (XXX) XXX-XXX-XXXX as well (which I need it to match).

Can you help me fix it so that it matches the formats
     XXX-XXX-XXXX, XXX-XXXX, (XXX) XXX-XXXX, (XXX) XXX-XXXX
without causing it to match other string formats which I don't want?

Upvotes: 1

Views: 7683

Answers (5)

Priyanka Acharya
Priyanka Acharya

Reputation: 141

^(((\d{3}) ?)|(\d{3}-))?\d{3}-\d{4}$^

this will work.

Upvotes: 0

santosh kore
santosh kore

Reputation: 986

I think so this is what you are looking for,

/^((((([0-9]{3})-)|((([0-9]{3}))\s))([0-9]{3})-([0-9]{4}))|(([0-9]{3})-([0-9]{4})))$/

It will work for below patterns XXX-XXX-XXXX, XXX-XXXX, (XXX) XXX-XXXX

Upvotes: -1

Bogatyr
Bogatyr

Reputation: 19333

Your specification is a bit confusing. Your last two cases appear the same:
XXX-XXX-XXXX
XXX-XXXX
(XXX) XXX-XXXX
(XXX) XXX-XXXX

(It looks like you're trying to match a phone number, is that right?) Assuming your last case is "(XXX)XXX-XXXX" (no space between area code and regular number, which I assume is the " ?" meaning optional space) then your RegExp is almost correct, just add two backslashes in front of the area code parentheses so they're matched as plain characters and not special grouping characters:

^((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}$

Note that your regular expression may not have come through correctly, I noticed that stack overflow removed a single backslash from the RE pattern, I had to type a double backslash "\\" in order to get a single backslash to come out in the message

Upvotes: 6

Rubens Farias
Rubens Farias

Reputation: 57996

Try this:

(\(\d{3}\) )?(\d{3}-){1,2}(\d{4})

Upvotes: 2

Palantir
Palantir

Reputation: 24182

You need to escape the parenthesis, like this: \( otherwise, they do not get matched and do captures instead.

Upvotes: 0

Related Questions