在做电商中,有些手机号是不能全部显示的,中间四位一般需要替换成*
这样处理有2中方法,a:substring来分割 b:正则验证
a:substring来分割手机号
public static void main(String[] args) {
String phone = "13123456789";
String phoneNumber = phone.substring(0, 3) + "****" + phone.substring(7, phone.length());
System.out.println("phone总长度:" + phone.length());
System.out.println("phone前3位:" + phone.substring(0, 3));
System.out.println("phone中4位:" + phone.substring(3, 7));
System.out.println("phone后4位:" + phone.substring(7, phone.length()));
System.out.println("phone中4*:" + phoneNumber);
}
效果图:
b:正则来验证手机号
public static void main(String[] args) {
String phone = "13123456789";
String phoneNumber = phone.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
System.out.println("正则phone中4*:" + phoneNumber);
}
效果图:
c:正则来验证身份证号
public static void main(String[] args) {
String idCard = "123456789987654321";
//$1、$2、……表示正则表达式里面第一个、第二个、……括号里面的匹配内容
String idCardNumber = idCard.replaceAll("(\\d{4})\\d{10}(\\w{4})","$1****$2");
System.out.println("身份证号长度:"+idCard.length());
System.out.println("正则idCard中4*:" + idCardNumber);
}
效果图: