Regular expression for phone number and extension only

I tried several times to write a regular expression validator for the asp.net intranet form web form. I tried to fake mine to no avail. The current one I'm using and trying to change is

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

I need to be allowed.

x1245
508-555-1212
5085551212
508 555 1212
508-555-1212 x1234
5085551212 x1243
508 555 1212 x1234

The only thing I looked at was the second on the list, the second down.

+4
source share
3 answers

It will do it.

(\d\d\d-?\s?\d\d\d-?\s?\d\d\d\d\s?)?(x\d\d\d\d)?

or shorter equivalent:

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

You want to combine the full phone number, optionally with a space / dash, and make it all optional, then enable the extension and make it optional.

+5
source

A similar pattern will match all your inputs:

\d{3}[- ]?\d{3}[- ]?\d{4}( x\d{4})?|x\d{4}

:

  • :

    • x

    — —

  • x

(^) end ($) , (, "foo x1234 bar"):

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

, , . 508-555 1212 : :

\d{3}([- ]?)\d{3}\1\d{4}( x\d{4})?|x\d{4}

(...) , , 1. \1 - , , 1.

+4

,

var regex = new Regex(@"^(?<number>\d{3}(?<separator>([\s-]|))\d{3}\k<separator>\d{4})?" +
                       "((?<=\d)\s|(?<=^)|(?=$))" +
                       "(?<extension>x\d{4})?(?<=.)$");
  • ^
  • (?<number>
  • \d{3} 3
  • (?<separator> start named group separator
  • ([\s-]|) , -
  • ) close group seperator
  • \d{3} 3
  • \k<separator>
  • \d{4} 4
  • )
  • ?
  • ((?<=d)\s|(<=^)|(?=$)) char ,
  • (?<extension>)
  • x\d{4} x, 4 .
  • )
  • ?
  • (?<=.) , ,
  • $
+2

All Articles