Tuesday, June 12, 2012

Better regular expression for phone numbers (multiple formats)

I'm often surprised at how often websites only accept a specific format for phone number input (U.S.) so I thought I would post a more flexible input format.

We want to allow users to enter phone numbers in formats like:

(123) 456-7890
123-456-7890
123.456.7890
1234567890

Using a regular expression, we can allow all these formats and more.


^\s*[(]?(?<AreaCode>\d{3})[)]?(\s*|[.-])(?<Prefix>\d{3})(\s*|[.-])?(?<LineNumber>\d{4})\s*$

Notice that we specify regular expression group names to easily pick up the phone number parts. In C#, this can be done like:

Code:
string prefix = match.Groups["Prefix"].Value;

Finally, here the some C# code to kick things off.

Code:
Regex rePhone = new Regex(@"^\s*[(]?(?<AreaCode>\d{3})[)]?(\s*|[.-])(?<Prefix>\d{3})(\s*|[.-])?(?<LineNumber>\d{4})\s*$");
Match match = rePhone.Match("123.456.7890");
Console.WriteLine(match.Success);

No comments:

Can't RDP? How to enable / disable virtual machine firewall for Azure VM

Oh no!  I accidentally blocked the RDP port on an Azure virtual machine which resulted in not being able to log into the VM anymore.  I did ...