1 public class Test 2 { 3 /** 4 * 用户身份证号码的打码隐藏加星号加* 18位和非18位身份证处理均可成功处理 参数异常返回null 5 * 6 * @param idCardNum 7 * 身份证号码 8 * @param front 9 * 需要显示前几位 10 * @param end 11 * 需要显示末几位 12 * @return 处理完成的身份证 13 */ 14 public static String idMask(String idCardNum, int front, int end) 15 { 16 // 身份证不能为空 17 if (StringUtil.isEmpty(idCardNum)) 18 { 19 return null; 20 } 21 // 需要截取的长度不能大于身份证号长度 22 if ((front + end) > idCardNum.length()) 23 { 24 return null; 25 } 26 // 需要截取的不能小于0 27 28 if (front < 0 || end < 0) 29 { 30 return null; 31 } 32 // 计算*的数量 33 int asteriskCount = idCardNum.length() - (front + end); 34 StringBuffer asteriskStr = new StringBuffer(); 35 for (int i = 0; i < asteriskCount; i++) 36 { 37 asteriskStr.append("*"); 38 } 39 String regex = "(\\w{" + String.valueOf(front) + "})(\\w+)(\\w{" + String.valueOf(end) + "})"; 40 return idCardNum.replaceAll(regex, "$1" + asteriskStr + "$3"); 41 } 42 43 }
测试效果:
4206**********6500