C# 正则表达式匹配所有美国电话号码格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18091324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:15:31  来源:igfitidea点击:

Regex to match all us phone number formats

c#regexvisual-studio

提问by confusedMind

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.

首先,我会说我在这里看到了很多例子并用谷歌搜索但没有发现匹配所有条件我正在寻找一些匹配前 3 不低于一些中间。请让我知道如何将所有这些放在一个地方。

(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

采纳答案by FlyingStreudel

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

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

回答by Karan Singh

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

回答by James Wierzba

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

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

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

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

回答by user1622895

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

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

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

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

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

请注意,由于 NANP 标准不是有效的电话号码,因此省略了两个示例值:区号以 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.

我所指的规则可以在 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.

回答by aloisdg moving to codidact.com

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.

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

.NETFiddle 上的演示

回答by Robert Green MBA

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

This allows:

这允许:

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

回答by Mahesh ML

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

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

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

777-777-7777

777-777-7777