方法一,简单的,不计算文字长度去设置脱敏
public static String dataDesensitization1(String content){String regex = "(.{2}).*(.{2})";return ReUtil.replaceAll(content, regex, matcher -> {try {if (CharSequenceUtil.isBlank(matcher.group())) {return "";}String start = matcher.group(1);String end = matcher.group(2);return start + "****" + end;} catch (Exception e) {return "";}});}
方法二,计算长度,取头尾三个文字,其余为**
return ReUtil.replaceAll(content, "(?<=.{2}).*(?=.{2})", matcher -> {try {if (CharSequenceUtil.isBlank(matcher.group())) {return "";}String middle = matcher.group();String desensitizedMiddle = ""; // 脱敏后的中间部分for (int i = 0; i < middle.length(); i++) {// 遍历中间部分的每个字符,只保留第一个和最后一个字符,其他用 "*" 代替if (i == 0 || i == middle.length() - 1) {desensitizedMiddle += middle.charAt(i);} else {desensitizedMiddle += "*";}}return desensitizedMiddle;} catch (Exception e) {return "";}});
一些其他的正则
PHONE = "((13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\\d{8})";
ID_CARD_FIFTEEN = "([1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{2}[0-9Xx])";//15位身份证
ID_CARD_EIGHTEEN = "([1-9]\\d{5}\\d{4}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx])";//18位身份证