简体   繁体   中英

Regex to match all us phone number formats

First of all i would say i have seen many example here and googled but none found that matches all the condition i am looking for some match top 3 not below some inbetween. Kindly let me know how to put all of them in one place.

(xxx)xxxxxxx
(xxx) xxxxxxx
(xxx)xxx-xxxx
(xxx) xxx-xxxx
xxxxxxxxxx
xxx-xxx-xxxxx

Using as:

  const string MatchPhonePattern =
           @"\(?\d{3}\)?-? *\d{3}-? *-?\d{4}";
            Regex rx = new Regex(MatchPhonePattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
            // Find matches.
            MatchCollection matches = rx.Matches(text);
            // Report the number of matches found.
            int noOfMatches = matches.Count;
            // Report on each match.

            foreach (Match match in matches)
            {

                tempPhoneNumbers= match.Value.ToString(); ;

             }

SAMPLE OUTPUT:

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

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

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

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

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

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.

^?\(?\d{3}?\)??-??\(?\d{3}?\)??-??\(?\d{4}?\)??-?$

This allows:

  • (123)-456-7890
  • 123-456-7890

for c#, the for US phone number validation should be like below

^\(?\d{3}?\)??-??\(?\d{3}?\)??-??\(?\d{4}?\)??-?$

777-777-7777

May be I am too late answering here but I have appended country code as prefix. People outside the state/country needs to add this code prior to phone number.I have made country code optional and one may enter the code inside small braces, without braces, with or without plus sign, hyphen as a delimiter to separate from rest of phone number. Regex and their samples are as follows:-

regex = '\(?\+?\d{1}\)\?\-?\(?\d{3}\)?-? *\d{3}-? *-?\d{4}';
Acceptable Samples :
(+1)-(111)-222-7878
+1-(111)-222-7878
+1(111)-222-7878
+1-111-222-7878
+1111-222-2323
1111-222-1212
1-111-222-1212
(111)-111-2232
111-222-3333
If you want to make country code mandatory then use following:-
regex = '\(?\+?\d{1}\)\?-?\(?\d{3}\)?-? *\d{3}-? *-?\d{4}';

I would approach the situation a bit differently and instead:

  • Step 1: extract the numbers you need from the given text. (skip if you have a list of numbers)
  • Step 2: Loop the numbers and clean up the format
  • Note: The last number is malformed but the code takes only the usable part.

Sample Text

Here are a list of contacts you can call:
Justin at +11 (949) 255 6458 or 1-909-885-4469.
Smith at (855) 270 4206 or 555-555-5555.
Sammy at 767.456.5289 or 9876548521x355.
Jill at 254.8695 or 56-852-6645 ext 22

Code

// Step 1: Match numbers from text;
let likePhoneRegex = /([0-9][0-9\s\.\-\(\)\[\]]+[0-9]{4})(\s*?(x|ext|extension)\s*[0-9]{2,})?/gi;
let matchData = sample.match(likePhoneRegex);

// Step 2: Loop and clean up numbers;
let phoneRegex = /(([0-9]*?)([2-9][0-9]{2})?([2-9][02-9]{2})([0-9]{4}))\b/;
let cleanupRegex = /(\+\.\.?)|(\+.*?\.\.)/;
let cleanData = [];
for( var i=0, il=matchData.length, num; i<il; i++){
   num = matchData[i].replace(/[^0-9\x]/g,'')
   var [ phone, ext ] = num.split('x');
   cleanData.push( phone.replace( phoneRegex, "+$2.$3.$4.$5" ).replace( cleanupRegex, '' ) + ( ext && ext.length > 0 ? ' x' + ext : '' ) );
}

Result

[
   "+11.949.255.6458",
   "+1.909.885.4469",
   "855.270.4206",
   "555.555.5555",
   "767.456.5289",
   "987.654.8521 x355",
   "254.8695",
   "852.6645 x22"
]

Please try this to allow below formats only

  • 0123456789
  • (123)456-7890
  • (123) 456-7890
  • 1234567890
  • 123-456-67897

string MatchPhonePattern = @"^(\d{3}-\d{3}-\d{4}|\d{10}|(\d{3})\s?\d{3}-\d{4})$"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM