假设您想在 JSON 响应中屏蔽密码。
{
"username":"test",
"password":1234
}
我们如何使用正则表达式来实现这一点。
输出应该是这样的
{
"username":"********",
"password": ********
}
在花了几个小时之后,找到了这个解决方案。
private static final String REGEX_FILTER_KEY = "[:]+((?=\\[)\\[[^]]*\\]|(?=\\{)\\{[^\\}]*\\}|\\\"[^\"]*\\\"|(\\d+(\\.\\d+)?))";
List<String> redactKeys = Collections.unmodifiableList(Arrays.asList("username", "password", "userId"));
private String redact(@NonNull String responseString) {
for (String key : redactingKeys) {
Matcher matcher = Pattern.compile(String.format("\"%s\"%s", key, REGEX_FILTER_KEY)).matcher(responseString);
if (matcher.find() && matcher.group(1) != null) {
responseString = responseString.replace(matcher.group(1), "**********");
}
}
return responseString;
}