Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expressions, Checking for a range of occurrences

Tags:

regex

I have a phone number I want to match against a regular expression. The format of the phone number must match this:

(123) 123-4567 x12345

The extension is optional. Also the extension must contain 1-5 numbers. Below is a regular expression I wrote that works.

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

I was wondering if there is a better way to check for the extension instead of

x\d\d?\d?\d?\d?

Can I say 1-5 occurrences of \d instead of the above some how ?

like image 312
Gabe Avatar asked Mar 30 '10 14:03

Gabe


2 Answers

Use this :

\d{1,5}

Check Limiting Repetitions paragraph on this link for more details.

like image 131
Thibault Falise Avatar answered Nov 15 '22 16:11

Thibault Falise


\d{1,5} will check for between 1 and 5 occurences

like image 36
Sam Holder Avatar answered Nov 15 '22 17:11

Sam Holder