Regex to match all us phone number formats

后端 未结 7 742
借酒劲吻你
借酒劲吻你 2020-12-03 03:32

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.

相关标签:
7条回答
  • 2020-12-03 03:50
     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;
            }
        }
    
    0 讨论(0)
  • 2020-12-03 03:50

    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();
    }
    
    0 讨论(0)
  • 2020-12-03 04:07

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

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

    777-777-7777

    0 讨论(0)
  • 2020-12-03 04:08
    ^?\(?\d{3}?\)??-??\(?\d{3}?\)??-??\(?\d{4}?\)??-?$
    

    This allows:

    • (123)-456-7890
    • 123-456-7890
    0 讨论(0)
  • 2020-12-03 04:12

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

    0 讨论(0)
  • 2020-12-03 04:14

    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

    0 讨论(0)
提交回复
热议问题