java手机号码合法性检查
时间: 2024-10-11 19:14:31 浏览: 54
在Java中,验证手机号码的合法性通常涉及到正则表达式的应用。中国的手机号码一般遵循一定的规则,例如11位数字,以13、14、15、16、17、18、19开头等。以下是一个简单的示例,展示了如何使用正则表达式检查中国大陆手机号码:
```java
import java.util.regex.Pattern;
public class Main {
private static final String PHONE_NUMBER_PATTERN = "^((13[0-9]|14[5|7]|15[^4\\D]|17[0-9]|18[0-9]|19[8|9])\\d{8})$";
public static boolean isValidPhoneNumber(String phoneNumber) {
Pattern pattern = Pattern.compile(PHONE_NUMBER_PATTERN);
return pattern.matcher(phoneNumber).matches();
}
public static void main(String[] args) {
System.out.println(isValidPhoneNumber("13912345678")); // 返回 true
System.out.println(isValidPhoneNumber("12345678901")); // 返回 false
}
}
```
这个例子中,`isValidPhoneNumber`函数会返回一个布尔值,如果输入的电话号码符合上述模式,则返回true,反之则返回false。
阅读全文
相关推荐


















