所以我想匹配信用卡号并以 6*4 格式屏蔽它们。这样只有前 6 个和最后 4 个字符可见。之间的字符将为“*”。我试图用像这样的面具来解决这个问题;
private static final String MASK = "$1***$3";
matcher.replaceAll(MASK);
但无法找到方法给我返回与组 $2 相同长度的中间星星。
然后我实现了下面的代码并且它有效。 但我想问是否有更短或更简单的方法来做到这一点。有人知道吗?
private static final String HIDING_MASK = "**********";
private static final String REGEX = "\\b([0-9]{6})([0-9]{3,9})([0-9]{4})\\b";
private static final int groupToReplace = 2;
private String formatMessage(String message) throws NotMatchedException {
Matcher m = Pattern.compile(REGEX).matcher(message);
if (!m.find()) throw new NotMatchedException();
else {
StringBuilder maskedMessage = new StringBuilder(message);
do {
maskedMessage.replace(m.start(groupToReplace), m.end(groupToReplace),
HIDING_MASK.substring(0, (m.end(groupToReplace) - m.start(groupToReplace))));
} while(m.find(m.end()));
return maskedMessage.toString();
}
}
编辑:这是要处理的示例消息。 "2017.08.26 20:51 [线程名称] [类名称] [方法名称] 信用卡持卡人 12345678901234567 02/2022 123........"
最佳答案
您可以使用以下代码简单地完成此操作:
str.replaceAll( "(?<=\\d{6})\\d(?=\\d{4})", "*" );
关于Java正则表达式匹配并用相同长度的字符替换匹配组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45885190/