zxl
19 小时以前 762eba0553917215d158eac8575ac0437c3216a7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package cn.lili.utils;
 
 
import cn.lili.common.utils.StringUtils;
 
/**
 * lmk-shop-java
 * 工具
 *
 * @author : zxl
 * @date : 2025-08-07 14:40
 **/
public class CommonUtil {
    public static String maskName(String name) {
        if (StringUtils.isBlank(name)) {
            return "";
        }
        // 规则:保留第一个字符,其余替换为 *
        return name.charAt(0) + StringUtils.repeat("*", name.length() - 1);
    }
    /**
     * 通用手机号脱敏:无论位数多少,均替换中间4位
     * 示例:
     * - 13812345678 → 138****5678
     * - 12345678 → 12****78
     * - 12345 → 1****5 (不足4位时全部替换)
     */
    public static String maskMobile(String mobile) {
        String digits = mobile.replaceAll("[^0-9]", "");
        int length = digits.length();
 
        // 2. 短号码直接隐藏
        if (length <= 4) {
            return "****";
        }
 
        // 3. 保留前2位和后2位,替换中间
        return digits.replaceAll("(\\d{2})\\d+(\\d{2})", "$1****$2");
    }
 
}