Regex to match all us phone number formats

Solution 1:

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

Solution 2:

 public bool IsValidPhone(string Phone)
    {
        try
        {
            if (string.IsNullOrEmpty(Phone))
                return false;
            var r = new Regex(@"^\(?([0-9]{3})\)?[-.●]?([0-9]{3})[-.●]?([0-9]{4})$");
            return r.IsMatch(Phone);

        }
        catch (Exception)
        {
            throw;
        }
    }

Solution 3:

To extend upon FlyingStreudel's correct answer, I modified it to accept '.' as a delimiter, which was a requirement for me.

\(?\d{3}\)?[-\.]? *\d{3}[-\.]? *[-\.]?\d{4}

in use (finding all phone numbers in a string):

string text = "...the text to search...";
string pattern = @"\(?\d{3}\)?[-\.]? *\d{3}[-\.]? *[-\.]?\d{4}";
Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
Match match = regex.Match(text);
while (match.Success)
{
    string phoneNumber = match.Groups[0].Value;
    //TODO do something with the phone number
    match = match.NextMatch();
}

Solution 4:

Help yourself. Dont use a regex for this. Google release a great library to handle this specific use case: libphonenumber. There is an online demo of the lib.

public static void Main()
{
    var phoneUtil = PhoneNumberUtil.GetInstance();
    var numberProto = phoneUtil.Parse("(979) 778-0978", "US");
    var formattedPhone = phoneUtil.Format(numberProto, PhoneNumberFormat.INTERNATIONAL);
    Console.WriteLine(formattedPhone);
}

Demo on .NETFiddle

Solution 5:

To add to all of the above suggestions, here's my RegEx that will enforce NANP standards:

((?:\(?[2-9](?(?=1)1[02-9]|(?(?=0)0[1-9]|\d{2}))\)?\D{0,3})(?:\(?[2-9](?(?=1)1[02-9]|\d{2})\)?\D{0,3})\d{4})

This regular expression enforces NANP Standard rules such as N11 codes are used to provide three-digit dialing access to special services, and thus excludes them using a conditional capture. It also accounts for up to 3 non-digit characters (\D{0,3}) in between sections, because I've seen some funky data.

From the provided testing data, here's the Output:

3087774825
(281)388-0388
(281)388-0300
(979) 778-0978
(281)934-2479
(281)934-2447
(979)826-3273
(979)826-3255
(281)356-2530
(281)356-5264
(936)825-2081
(832)595-9500
(832)595-9501
281-342-2452

Note that there were two sample values omitted due to not being valid phone numbers by NANP Standards: Area Code begins with 1

1334714149
1334431660

The rule I am referring to can be found on the National NANPA's website's Area Codes page stating, The format of an area code is NXX, where N is any digit 2 through 9 and X is any digit 0 through 9.