我正在尝试编写正则表达式,如果提供所有相同的数字作为电话号码,它应该失败。当我提供以下输入时,它通过了验证。
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}");
}
说明
正则表达式分为两部分:
(?!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-7890
或 123.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/