为身份证打码
1 package com.example.test; 2 3 import org.springframework.util.StringUtils; 4 5 public class IdCardTest { 6 public static void main(String[] args) { 7 //身份证号 8 String id ="22070219961005081x"; 9 //开始的结束长度 10 int start = 6; 11 //结束截取长度 12 int end =4; 13 //打码长度的方法 14 String idNewNum = cardMask(id, start, end); 15 System.out.println(idNewNum); 16 } 17 public static String cardMask(String idNum,int start,int end){ 18 if (StringUtils.isEmpty(idNum)){ 19 return "身份证号不能为空"; 20 } 21 if(start + end > idNum.length()){ 22 return "截取长度不能大于身份证的长度"; 23 } 24 if (start <0 || end <0){ 25 return "请定义开始显示数目及结束显示位数"; 26 } 27 //打码*号的数量 28 int x = idNum.length() -start - end; 29 StringBuffer idNewNum = new StringBuffer(); 30 for (int i = 0; i <x ; i++) { 31 idNewNum.append("*"); 32 } 33 String regex = "(\\w{" + String.valueOf(start) + "})(\\w+)(\\w{" + String.valueOf(end) + "})"; 34 return idNum.replaceAll(regex,"$1" + idNewNum + "$3"); 35 } 36 }