正则表达式匹配所有我们的电话号码格式

首先,我会说我在这里看到了许多例子和谷歌搜索,但没有发现匹配所有条件我正在寻找一些匹配前三名不低于一些中间。 请告诉我如何将所有这些放在一个地方。

(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 

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

为了扩展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(); } 

要添加上述所有建议,这是我的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.

帮助自己。 不要使用正则表达式。 谷歌发布了一个很棒的库来处理这个特定的用例: 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); } 

在.NETFiddle上演示