第一種,使用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