I built a regex to capture the value from the pattern, where pattern is to identify the json and fetch value from it. But along with the expected groups, it is also capturing the empty strings in the group.
Regex:
(?<=((?i)(finInstKey)":)["]?)(.*?)(?=["|,|}])|(?<="((?i)finInstKey","value":)["]?)(.*?)(?=["|,|}])
input:
- {"finInstKey":500},{"name":"finInstKey","value":12345678900987654321}
- {finInstKey":"500"},{"name":"finInstKey","value":"12345678900987654321"}
for these inputs, input 2 also captures the empty string along with the expected values.
actual output:
500
12345678900987654321
500
12345678900987654321
expected output:
500
12345678900987654321
500
12345678900987654321
As of now, I have handled it manually in the Java code, but it would be nice if regex won't capture the empty strings. what changes should I make in the regex to get expected output.
Mainly, I want this to replaceAll groups with masked value "****".
My piece of code:
public class RegexTester {
private static final String regex = "(?<=((?i)(%s)\":)[\"]?)(.*?)(?=[\"|,|}])|(?<=\"((?i)%s\",\"value\":)[\"]?)(.*?)(?=[\"|,|}])";
public static void main(String[] args) {
String field = "finInstKey";
String input = "{\"finInstKey\":500},{\"name\":\"finInstKey\",\"value\":12345678900987654321}{finInstKey\":\"500\"},{\"name\":\"finInstKey\",\"value\":\"12345678900987654321\"}";
try {
Pattern pattern = Pattern.compile(String.format(regex, field, field));
Matcher matcher = pattern.matcher(input);
// System.out.println(matcher.replaceAll("****"));
while (matcher.find()) {
System.out.println(matcher.group());
}
} catch (Exception e) {
System.err.println(e);
}
}
}