自已Java编写的隐藏手机号、身份证号中间几位的方法

public static void main(String[] args) {
    String phone ="18516638266";
    System.out.println(phone);
    System.out.println(getEncryptCode(phone,3,4));
}

/**
 * @param code 要隐藏显示的字符串
 * @param head 前面保留的位数
 * @param tail 后面保留的位数
 * @return 处理后的字符串
 */
public static String getEncryptCode(String code,int head,int tail){
    // 中间要隐藏的位数
    int body = code.length() - head - tail;
    // 将字符串拆成三部分,并指定每部分长度的正则表达式
    String regexVar = "(\\w{%d})(\\w{%d})(\\w{%d})";
    String regex = String.format(regexVar, head, body, tail);
    // 获取字符串中间要隐藏的部分,并替换成对应长度的*
    String bodyPart = code.replaceAll(regex, "$2");
    String bodyEncrypt = bodyPart.replaceAll("\\w", "*");
    // 处理生成字符串replacement = "$1*****$3" 中间是对应长度的*号
    String replacement = String.format("$1%s$3", bodyEncrypt);
    return code.replaceAll(regex, replacement);
}
控制台打印结果: 18516638266 185****8266
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值