I'm trying to mask an access token with stars. The response payload is converted to a string. I need to match the token pattern with the string and replace the token value with stars.
{"accessToken":"knjnandHJHJBhjHJhjGhjghjGHJGhjgHJGjIG6gg8F68c6F6f6F6d67f79GV78INy8c5SV8n98f5D6g89Byf5446f678u8878GF756d57899bVY7TC6c7VY8UBi9u8","accessTokenExpirationTime":1800}
This should be like below
{"accessToken":"*********************************************************************************************************************","accessTokenExpirationTime":1800}
The code below cannot find a match and replace
String payload = PAYLOAD_STRING;
Pattern pattern = Pattern.compile("[a-zA-Z0-9]{126}$");
Matcher matcher = pattern.matcher(payload);
String result = matcher.replaceAll("<h1>*</h1>");
System.out.println(result);
You can use Pattern & Matcher like this:
String payload = ....;
Pattern pattern = Pattern.compile("\"accessToken\":\"([a-zA-Z0-9]+)\"");
Matcher matcher = pattern.matcher(payload);
if (matcher.find()) {
String accessToken = matcher.group(1);
String maskedToken = "*".repeat(accessToken.length());
String result = payload.replace(accessToken, maskedToken);
System.out.println(result);
} else {
System.out.println("Access token not found.");
}