使用正则表达式来掩盖Java中的最后4位数 [英] Use regular expression to mask last 4 digit in Java

查看:278
本文介绍了使用正则表达式来掩盖Java中的最后4位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想掩盖身份证号码的最后4位数字(hkid)
A123456(7) - > A123 ***(*)

I would like to mask the last 4 digits of the identity number (hkid) A123456(7) -> A123***(*)

我可以通过以下方式执行此操作:

I can do this by below:

hkid.replaceAll("\\d{3}\\(\\d\\)", "***(*)")

但是,我的正则表达式是否真的可以匹配最后4位数并替换为*?

However, can my regular expression really can match the last 4 digit and replace by "*"?

hkid.replaceAll(regex, "*")

请帮助,谢谢。

Jessie

推荐答案

就个人而言,我不会用正则表达式来做:

Personally, I wouldn't do it with regular expressions:

char[] cs = hkid.toCharArray();
for (int i = cs.length - 1, d = 0; i >= 0 && d < 4; --i) {
  if (Character.isDigit(cs[i])) {
    cs[i] = '*';
    ++d;
  }
}
String masked = new String(cs);

这是从字符串的末尾开始,查找数字字符,用<$取代C $ C> * 。一旦找到4(或到达字符串的开头),它就会停止迭代,并构建一个新的字符串。

This goes from the end of the string, looking for digit characters, which it replaces with a *. Once it's found 4 (or reaches the start of the string), it stops iterating, and builds a new string.

这篇关于使用正则表达式来掩盖Java中的最后4位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆