Posted By

wizard04 on 07/31/08


Tagged

regex javascript phone


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

Scooter
letosword
LeeRJohnson


Regular Expressions for U.S. Phone Numbers


 / Published in: Regular Expression
 

URL: http://en.wikipedia.org/wiki/North_American_Numbering_Plan

(Created for JavaScript)

These are rather forgiving. Spaces, dashes, or periods are allowed as separators. Extensions can be recognized by several strings (#, x, x., ext, ext., extension).

Area code: $1$2 Exchange code: $3 Station code: $4 Extension / Extra characters: $5

Separators are not accepted within the $3$4$5 portion of a vanity number.

Example: (540) 555-0123 ext.678 --> ($1$2) $3-$4 ext.$5 Example: 1-800-GOODFOOD --> 1-$1$2-$3$4$5

  1. //10-digit phone number
  2. ^(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})$
  3.  
  4. //10-digit phone number, extension allowed
  5. ^(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$
  6.  
  7. //7 or 10-digit phone number
  8. ^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})$
  9.  
  10. //7 or 10-digit phone number, extension allowed
  11. ^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$
  12.  
  13. //10-digit phone number, vanity (alphanumeric) allowed
  14. ^(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?([2-9a-z]1[02-9a-z]|[2-9a-z][02-9a-z]1|[2-9a-z][02-9a-z]{2})([0-9a-z]{4})$
  15.  
  16. //10-digit phone number, vanity allowed, extra characters allowed at end
  17. ^(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?([2-9a-z]1[02-9a-z]|[2-9a-z][02-9a-z]1|[2-9a-z][02-9a-z]{2})([0-9a-z]{4})([0-9a-z]*)$

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: wizard04 on August 12, 2008

Fixed some stupid mistakes (i.e., the commas) and made it a bit more efficient.

You need to login to post a comment.