regex for phone number

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
global_erp_solution
Forum Commoner
Posts: 25
Joined: Sun Jul 08, 2012 6:47 am

regex for phone number

Post by global_erp_solution »

Rules:
1. must start with number
2. sum of numeric must be between 7-12 inclusive
3. other valid non-numeric characters include space (" ") and hyphens ("-")
4. no more than one consecutive valid non-numeric characters allowed ("1 2-3" is allowed, "1-2" is allowed, but "1--2" is not, "1- 2" is also not allowed)

right now my regex is this:
\\d([- ]?\\d[- ]?){6,11}

but it passed the test 123--4567. What's wrong? thanks
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: regex for phone number

Post by requinix »

Would it not be a lot easier to just strip out all non-numeric characters and validate the length? Then format it however you want.
User avatar
tr0gd0rr
Forum Contributor
Posts: 305
Joined: Thu May 11, 2006 8:58 pm
Location: Utah, USA

Re: regex for phone number

Post by tr0gd0rr »

You might need to run a regex for 3 and a separate regex for 4.
thewebhostingdir
Forum Newbie
Posts: 18
Joined: Fri Jul 17, 2009 1:15 am

Re: regex for phone number

Post by thewebhostingdir »

Try following regex :

((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}
AccuWebHosting.Com - Windows VPS Hosting
ASP.NET 3.5 | SQL 2005 Database | US Based Hosting Company | 24 X 7 Support | Daily Backups | Uptime Guarantee | Affiliates - $50 Per Sale |
Brick7.com | TheWebHostingDir.com
Post Reply