第一种,使用java工具类StrUtil中的hide方法如:
// 手机号码 第4-7位脱敏
String phone = StrUtil.hide("18330303030", 3, 7);
其中hide方法具体实现如下:
/** * 替换指定字符串的指定区间内字符为"*" * * @param str 字符串 * @param startInclude 开始位置(包含) * @param endExclude 结束位置(不包含) * @return 替换后的字符串 * @since 4.1.14 */ public static String hide(CharSequence str, int startInclude, int endExclude) { return replace(str, startInclude, endExclude, '*'); }
接着replace方法实现如下:
/**
* 替换指定字符串的指定区间内字符为固定字符
*
* @param str 字符串
* @param startInclude 开始位置(包含)
* @param endExclude 结束位置(不包含)
* @param replacedChar 被替换的字符
* @return 替换后的字符串
* @since 3.2.1
*/
public static String replace(CharSequence str, int startInclude, int endExclude, char replacedChar) {
if (isEmpty(str)) {
return str(str);
}
final int strLength = str.length();
if (startInclude > strLength) {
return str(str);
}
if (endExclude > strLength) {
endExclude = strLength;
}
if (startInclude > endExclude) {
// 如果起始位置大于结束位置,不替换
return str(str);
}
// 初始化一个长度为11的字符数组
final char[] chars = new char[strLength];
for (int i = 0; i < strLength; i++) {
if (i >= startInclude && i < endExclude) {
chars[i] = replacedChar;
} else {
chars[i] = str.charAt(i);
}
}
return new String(chars);
}
输出结果为:183****3030
第二种方式:使用正则表达式:
private static String desensitizeDelectronicsAccountNo(String phoneNo){
if (!Strings.isNullOrEmpty(phoneNo)) {
if (phoneNo.length() == 11){
phoneNo = phoneNo.replaceAll("(\\w{3})\\w*(\\w{4})", "$1*****$2");
}
}
18330303030