java - 对于所有相同的号码,电话号码验证应该失败

标签 java regex

我正在尝试编写正则表达式,如果提供所有相同的数字作为电话号码,它应该失败。当我提供以下输入时,它通过了验证。 999.999.9999999-999-9999999 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}");
}

说明

正则表达式分为两部分:

(?!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 来跳过任何分隔符字符。

关于java - 对于所有相同的号码,电话号码验证应该失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53636022/

相关文章:

java - 如何通过 Selenium 关闭对话框?

java - 逆向工程与 hibernate 工具的多对一单向关联的问题

python - 删除文本文件中以 `#|...|#` 为界的注释 block - python

javascript - 正则表达式问题模式不起作用

java - 如何为 springboot 2.0.2 启用 Httpclient

java - Jenkins Build - 找不到 Java 类

java - 在 jTextArea 中打印 jRadioButtons

javascript - 使用正则表达式获取 CSS 值

c# - 我可以结合正则表达式问题 ([\\d]*$) 和 ([\\d]*)c$

javascript - 如何处理正则表达式中的可选组并删除结果的尾随空格