regular expressions - phone number and extension

We are trying to use regular expressions to check a valid phone number.  We have a pattern but we want to add an option for an extension.
phonePattern = @"\((?<AreaCode>\d{3}) \)?[-\s]? (?<Prefix>\d{3}) [-.] (?<Number>\d{4})";
would this work
phonePattern = @"\((?<AreaCode>\d{3}) \)?[-\s]? (?<Prefix>\d{3}) [-.] (?<Number>\d{4}) x?<ext>\d{10}";
Here are some valid examples for phone numbers
555-123-4567
555-123-4567 x1234
555-123-4567 x 1234
555-123-4567 x778942
tampsystemsAsked:
Who is Participating?
 
numberkruncherConnect With a Mentor Commented:
Sorry, I just noticed that you wanted an "x" on your extension number.

The below regex matches:

(123) 123-4567 x1234
(123) 1234567 x1234
123-4567 x1234
1234567 x1234

(123) 123-4567 x 1234
(123) 1234567 x 1234
123-4567 x 1234
1234567 x 1234

(123) 123-4567x 1234
(123) 1234567x 1234
123-4567x 1234
1234567x 1234

(123) 123-4567x1234567890
(123) 1234567x1234567890
123-4567x1234567890
1234567x1234567890

((\d{3}|\(\d{3}\))?(\s|\-)?\d{3}(\s|\-)?\d{4})(\s?x(\s)?\d{1,10})?

Open in new window

0
 
tosanjayCommented:
ok. So, valid examples are:
555-123-4567
555-123-4567 x1234
555-123-4567 x 1234
555-123-4567 x778942
e.g. <3 digits><-><3 digits><-><4 digits>#extension Part#<space><x><optional space><4 to 6 digits>

let me put regexp in a simpler form.
\d{3}\-\d{3}\-\d{4}(\sx\s?\d{4,6})?

this will match all the number formats, mentioned above. A better solution can be made if you know the next character after a number e.g. new line/carriage return.
Hope this helps.
0
 
tampsystemsAuthor Commented:
I want to be able to support () spaces and dashes
i.e.
(555) 123 4567
(555) 123-4567
555 123 4567
555 123-4567
555-123-4567
5551234567
555 1234567
555123 4567
And the optional extension number
0
 
numberkruncherCommented:
The following regular expression matches your formats, and the following:

(123) 123-4567 1234
(123) 1234567 1234
(123) 123-4567
(123) 1234567
123-4567 1234
1234567 1234
123-4567
1234567

((\d{3}|\(\d{3}\))?(\s|\-)?\d{3}(\s|\-)?\d{4})((\s|\-)?\d{4})?

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.