Phone number regular expressions exact format

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.)

Leave a Comment