-5

I'm looking for a regular expression that will match any of these phone number formats but ONLY these formats. For example, (999-999-999 should not work. I know how to use ? for optional however I want the second ) to be mandatory only if the number starts with (, and the second ) should not be optional if the number does not start with a (. Also wherever there is a black space, there could be an unlimited number of spaces. (999) 999-999 is valid but (999 ) 999-9999 is not

999-999-9999
999 999 9999
999 999-9999
9999999999
999 9999999
(999) 999-9999
(999) 999 9999
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
  • 2
    You'll need to show what you've tried. Even if you just make up some stuff that looks vaguely like regex. But some effort on your part is expected. – lintmouse Oct 14 '15 at 16:30
  • Possible duplicate of [Phone validation regex](http://stackoverflow.com/questions/8634139/phone-validation-regex) – Jose Ricardo Bustos M. Oct 14 '15 at 18:14

1 Answers1

1

I suggest to buy yourself this book:

http://www.amazon.ca/Regular-Expressions-Cookbook-Jan-Goyvaerts/dp/1449319432/ref=sr_1_1?ie=UTF8&qid=1444846344&sr=8-1&keywords=regular+expression+cookbook

if you are struggling for such a basic regex (which can be found pretty much everywhere on the net). It's a cookbook, meaning that the solutions can be use directly as they are in the book.

From page 249:

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

You have three capture groups:

1st and 2nd ([0-9]{3}) 3rd ([0-9]{4})

You can use those capture group to return the different section of the phone number. Use non-capturing group (?:) for increased performance (in that context that should not be necessary unless you use a loop).

That if for optional parenthesis \(? and \)?.

You need to escape the parenthesis since it is use for grouping in regex. The question mark (?) makes the preceding element or group optional.

Use [- ]? to make space and hyphen optional between the digits sequence.

Additional note: That is a pretty generic regex, so it should be compatible with any programming language.

Therefor, you should know that event though the general structure of regular expression is pretty much the same, there are significant difference among the different language implementation for fancier/advanced functionalities.

Next time, you should also specify for which programming language you want the regex (by example: PHP, Javascript, etc.)