すべて同じ番号の電話番号検証万一失敗

ジェイ:

私はすべて同じ番号が電話番号として提供されている場合、それは失敗する書き込み正規表現にしようとしています。私は入力以下とが供給されると、それが検証に合格します。999.999.9999または999-999-9999または999 999 9999検証に失敗する方法についての正規表現パターン上の任意の提案は、それはすべて同じ番号を供給しました。

    private static boolean validatePhoneNumber(String phoneNo) {
        //validate phone numbers of format "1234567890"
        if (phoneNo.matches("\\d{10}")) return true;

        //validating phone number with -, . or spaces
        else if(phoneNo.matches("\\d{3}[-\\.\\s]\\d{3}[-\\.\\s]\\d{4}")) return true;

        //Invalid phone number where 999.999.9999 or 999-999-9999 or 999 999 9999
        else if(phoneNo.matches"(\\D?[0-9]{3}\\D?)[\\s][0-9]{3}-[0-9]{4}")) return false;

        //return false if nothing matches the input
        else return false;

    }
アンドレアス:

あなたは、単一の正規表現でそれを行うことができます。

(?!(\d)\1{2}\D?\1{3}\D?\1{4})\d{3}([-. ]?)\d{3}\2\d{4}

Javaコードとして、あなたの方法は次のようになります。

private static boolean validatePhoneNumber(String phoneNo) {
    // Check if phone number is valid format (optional -, . or space)
    // e.g. "1234567890", "123-456-7890", "123.456.7890", or "123 456 7890"
    // and is that all digits are not the same, e.g. "999-999-9999"
    return phoneNo.matches("(?!(\\d)\\1{2}\\D?\\1{3}\\D?\\1{4})\\d{3}([-. ]?)\\d{3}\\2\\d{4}");
}

説明

正規表現は、2つの部分であります:

(?!xxx)yyy

yyy一部は以下のとおりです。

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

どの手段:

\d{3}     Match 3 digits
([-. ]?)  Match a dash, dot, space, or nothing, and capture it (capture group #2)
\d{3}     Match 3 digits
\2        Match the previously captured separator
\d{4}     Match 4 digits

それは例えば一致すること。この意味123-456-7890123.456.7890、ではなく、123.456-7890

(?!xxx)一部はゼロ幅の負の先読みである場合、すなわち、それは一致するxxx表現が一致していない、とxxx一部です:

(\d)\1{2}\D?\1{3}\D?\1{4}

どの手段:

(\d)   Match a digit and capture it (capture group #1)
\1{2}  Match 2 more of the captured digit
\D?    Optionally match a non-digit
\1{3}  Match 3 more of the captured digit
\D?    Optionally match a non-digit
\1{4}  Match 4 more of the captured digit

第二部は、既にセパレータを検証しているので、先読み負のは、単によりリラックスし使用している\D任意の区切り文字をスキップします。

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=223245&siteId=1