【问题标题】:Regex to match all us phone number formats正则表达式匹配我们所有的电话号码格式
【发布时间】:2013-08-06 22:03:10
【问题描述】:

首先,我会说我在这里看到了很多示例并进行了谷歌搜索,但没有找到符合我正在寻找的匹配前 3 名而不低于中间值的所有条件。 请让我知道如何将它们全部放在一个地方。

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

用作:

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

             }

样本输出:

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

【问题讨论】:

    标签: c# regex visual-studio


    【解决方案1】:

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

    【讨论】:

    • 嘿工作得很好:),只是一个问题是很好的添加一个 xxxxxxxxxx 因为我认为它可能会采用随机数这可能吗?谷歌分析数字等?
    • 它还将捕获任何长度为 10 位的数字字符串,无论这是否是您想要的行为取决于您,可能值得对匹配的数字进行某种验证如果您选择允许它们,则使用正则表达式。
    • 具有讽刺意味的是,在几个 SO 答案中,这个最能满足我的需求,所以感谢您的回答。仅供参考,我也对匹配点和空格感兴趣,所以 \(?\d{3}\)?[. -]? *\d{3}[. -]? *[. -]?\d{4} 为我做了这个伎俩。
    • 我只想将其限制为 1234567890,123-456-7890。那么我对正则表达式不太了解的正则表达式是什么
    • 以下应该返回 false(电话号码超过 10 位),但返回 true:Regex.IsMatch("(012)34568902", @"(?\d{3})? -? *\d{3}-? *-?\d{4}" ) Regex.IsMatch("01234568902", @"(?\d{3})?-? *\d{3}-? * -?\d{4}" ) ?Regex.IsMatch("012 345 68902", @"(?\d{3})?-? *\d{3}-? *-?\d{4}" ) 这应该可以满足您的需求:@"^(?([0-9]{3}))?[-. ]?([0-9]{3})[-. ]?([0- 9]{4})$"authorcode.com/…
    【解决方案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;
            }
        }
    

    【讨论】:

      【解决方案3】:

      为了扩展 FlyingStreudel 的正确答案,我将其修改为接受 '.'作为分隔符,这是我的要求。

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

      正在使用(查找字符串中的所有电话号码):

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

      【讨论】:

        【解决方案4】:

        帮助自己。不要为此使用正则表达式。 Google 发布了一个很棒的库来处理这个特定的用例:libphonenumber。有一个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

        【讨论】:

          【解决方案5】:

          要添加以上所有建议,这是我的 RegEx,它将强制执行 NANP 标准:

          ((?:\(?[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})
          

          此正则表达式强制执行 NANP 标准规则,例如 N11 codes are used to provide three-digit dialing access to special services,因此使用条件捕获将它们排除在外。它还在部分之间最多占 3 个非数字字符 (\D{0,3}),因为我看到了一些时髦的数据。

          根据提供的测试数据,输出如下:

          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
          

          请注意,由于不是 NANP 标准的有效电话号码,因此省略了两个示例值:区号以 1 开头

          1334714149
          1334431660
          

          我所指的规则可以在 National NANPA 网站的区号页面上找到,说明 The format of an area code is NXX, where N is any digit 2 through 9 and X is any digit 0 through 9.

          【讨论】:

            【解决方案6】:
            ^?\(?\d{3}?\)??-??\(?\d{3}?\)??-??\(?\d{4}?\)??-?$
            

            这允许:

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

            【讨论】:

            • 那我该如何使用呢?
            【解决方案7】:

            对于 c#,美国电话号码验证应如下所示

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

            777-777-7777

            【讨论】:

              【解决方案8】:

              我会以不同的方式处理这种情况,而是:

              • 第 1 步:从给定文本中提取您需要的数字。 (如果您有数字列表,请跳过)
              • 第 2 步:循环数字并清理格式
              • 注意:最后一个数字格式错误,但代码只占用可用部分。

              示例文本

              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
              

              代码

              // 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 : '' ) );
              }
              

              结果

              [
                 "+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"
              ]
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2010-12-16
                • 2011-09-22
                • 1970-01-01
                • 1970-01-01
                • 2020-01-18
                • 1970-01-01
                • 2022-01-03
                • 1970-01-01
                相关资源
                最近更新 更多