[英]Java Regex Match and Replace matched group with characters of same length
所以我想匹配信用卡号码并以6 * 4格式掩盖它们。 这样只能显示前6个和后4个字符。 之间的字符将是'*'。 我试着用MASK来解决这个问题;
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 [主题名称] [类别名称] [MethodName]信用卡持卡人12345678901234567 02/2022 123 .........”
private String formatMessage(String message) throws NotMatchedException {
if (message.matches(".*\\b\\d{13,19}\\b.*")) {
return message.replaceAll("(?:[.\\b]*)(?<=\\d{6})\\d(?=\\d{4})(?:[.\\b]*)", "*");
} else {
throw new NotMatchedException() ;
}
}
您只需使用以下代码即可:
str.replaceAll( "(?<=\\d{6})\\d(?=\\d{4})", "*" );
可读但不酷。
String in = "1234561231234";
String mask = in
.replaceFirst("^\\d{6}(\\d+)\\d{4}$", "$1")
.replaceAll("\\d", "\\*");
String out = in
.replaceFirst("^(\\d{6})\\d+(\\d{4})$", "$1" + mask + "$2");
如果您的文本包含多个可变长度的信用卡号,则可以使用以下内容:
str.replaceAll( "\\b(\\d{13,19})\\b", "\u0000$1\u0000" )
.replaceAll( "(?<=\\d{6})(?<=\u0000\\d{6,14})\\d(?=\\d{4,12}\u0000)(?=\\d{4})", "*" )
.replaceAll( "\u0000([\\d*]+)\u0000", "$1" );
但不是真的可读,但这一切都在一起。
一个16字符“数字”的简单解决方案:
String masked = num.substring(0,6) + "******" + num.substring(12,16);
对于任意长度的字符串(> 10):
String masked = num.substring(0,6)
+ stars(num.length() - 10)
+ num.substring(num.length() - 6);
...其中stars(int n)
返回n
星的String
。 请参阅在java中重复String的简单方法 - 或者如果您不介意限制9星, "*********".substring(0,n)
使用StringBuffer
并覆盖所需的字符:
StringBuffer buf = new StringBuffer(num);
for(int i=4; i< buf.length() - 6) {
buf.setCharAt(i, '*');
}
return buf.toString();
你也可以使用buf.replace(int start, int end, String str)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.