Showing posts with label phone number. Show all posts
Showing posts with label phone number. Show all posts

Wednesday, March 30, 2016

Best regular expression for phone number that accepts many variations

Here is a handy regular expression that will accept many variations of an U.S. phone number, allowing the input to be somewhat flexible.

^\s*[(]?\d{3}[).\-]?\s*\d{3}(\s*|[.\-]?)\d{4}\s*$

// accepted
8015551212
801 555 1212
(801)5551212
801.555.1212
801.555-1212
801-555-1212
(801)555-1212
(801) 555-1212
801-555.1212
(801 555 1212
(801 555 1212
801)5551212

// rejected
8015551212a
80155512122
801a5551212
8015;551212
(801))5551212

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);

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 ...