帮我用java写一段身份证和手机号码的校验代码
时间: 2024-04-10 08:32:58 浏览: 114
当然可以!以下是一个简单的Java代码示例,用于验证身份证号码和手机号码的格式是否正确:
```java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Validator {
public static boolean isValidIDCard(String idCard) {
String pattern = "^\\d{17}(\\d|x|X)$";
Pattern regex = Pattern.compile(pattern);
Matcher matcher = regex.matcher(idCard);
return matcher.matches();
}
public static boolean isValidPhoneNumber(String phoneNumber) {
String pattern = "^1[3-9]\\d{9}$";
Pattern regex = Pattern.compile(pattern);
Matcher matcher = regex.matcher(phoneNumber);
return matcher.matches();
}
public static void main(String[] args) {
String idCard = "11010119900101001X";
String phoneNumber = "13812345678";
if (isValidIDCard(idCard)) {
System.out.println("身份证号码格式正确");
} else {
System.out.println("身份证号码格式错误");
}
if (isValidPhoneNumber(phoneNumber)) {
System.out.println("手机号码格式正确");
} else {
System.out.println("手机号码格式错误");
}
}
}
```
上述代码中,我们使用了正则表达式来验证身份证号码和手机号码的格式。`isValidIDCard` 方法用于验证身份证号码,`isValidPhoneNumber` 方法用于验证手机号码。在 `main` 方法中,我们通过调用这两个方法来进行验证,并输出相应的结果。
请注意,以上代码只验证了身份证号码和手机号码的基本格式,对于身份证号码的规则校验和手机号码的真实有效性校验,仍需进一步处理。
阅读全文
相关推荐















