2013-08-06 11 views
12

まず最初に、私はここで多くの例を見てきましたが、グーグルが見つかりましたが、私はいくつかのマッチトップ3を探しています。 それらをすべて1か所に置く方法を教えてください。Regexは私たち全員の電話番号フォーマットに一致します

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

      } 

サンプル出力:として使用

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

FlyingStreudelの正解時に拡張するには

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 

答えて

31

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

+0

回答ありがとうございました – confusedMind

+3

問題はないので、だから遅れてますます面白くなっているようです。私はファンだとは言えません。 – FlyingStreudel

+0

ちょっとうまく動作します:)ちょうど質問は、私はそれが可能な乱数を取っているかもしれないと思うので、xxxxxxxxxxと1つを追加すると良いですか?グーグル分析番号など? – confusedMind

6
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

を、私は受け入れるようにそれを修正 ''区切り文字として、これは私の必要条件でした。

使用中の

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

上記の提案のすべてに追加するには、ここでは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}) 

この正規表現は、N11 codes are used to provide three-digit dialing access to special servicesなどのNANP標準ルールを適用しているため、条件付きキャプチャを使用して除外しています。また、セクション間に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規格で有効な電話番号をされないように省略し、2つのサンプル値があったこと:エリアコードは1

1334714149 
1334431660 
で始まりますが、

私が参照しているルールは、国立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.

関連する問題