java字符串内容脱敏
1.手机号脱敏,只保留后四位
String test3(String sourceStr, int begin, int end, String replacement){
if (sourceStr == null) {
return "";
}
if (replacement == null) {
replacement = "*";
}
int replaceLength = end - begin;
if (StringUtils.isNotBlank(sourceStr) && replaceLength > 0) {
StringBuilder sb = new StringBuilder(sourceStr);
sb.replace(begin, end, StringUtils.repeat(replacement, replaceLength));
return sb.toString();
} else {
return sourceStr;
}
}
String s = test3(str, 0,str.length() - 4, null);
结果:*******9303
注:这里可以按照需求传参,比如前三后四手机号脱敏等
2.格字脱敏
void test1() {
String phone = "15936159303";
char[] array = phone.toCharArray();
StringBuilder str= new StringBuilder();
for (int i = 0; i < array.length; i++) {
if(i%2==1){
str.append("*");
continue;
}
str.append(array[i]);
}
System.out.println(str);
}
结果:1* 9 * 6 * 5 * 3 * 3
3.若出现连续n位(不含n位)以上数字时,只保留后四位,其他的脱敏展示
Pattern p = Pattern.compile("\\d{4,}");//这个4是指连续数字的最少个数
String u = "aaa11100.00004222222hhah11111";
StringBuilder str=new StringBuilder();
Matcher m = p.matcher(u);
while (m.find()) {
String x = "";
String v = "";
String i = "";
System.out.println(m.group());
if(m.group()!=null){
x = m.group().substring(m.group().length()-4, m.group().length());
v = m.group().substring(0, m.group().length()-4);
for (int j = 0; j < v.length(); j++) {
i += "*";
}
u = u.replaceFirst(m.group(), i + x);
}
}
System.out.println(u);
结果:aaa*1100.******2222hhah1111
注:这里的n是指几位连续几位以上的数字,只需修改正则表达式即可