Reputation: 2240
Requirements:
For each Json field where key matches specified constant replace value with another constant.
{"regular":"a", "sensitive":"b"}
Parameters "sensitive", "*****". Expected:
{"regular":"a", "sensitive":"*****"}
Values may, or may not have double quotes around them. Replacement constant is double quouted always. Json may be malformed. Java implementation preferably.
Key comparison is case insensitive.
Upvotes: 0
Views: 3553
Reputation: 12438
You can use the following regex:
String t= "{\"regular\":\"a\", \"sensitive\":\"b\"}"; //{"regular":"a", "sensitive":"b"}
String r = t.replaceAll("(\\s*)\"?sensitive\"?\\s*:\\s*\"?b\"?\\s*", "$1\"sensitive\":\"*****\"");
System.out.println("output "+r); //output {"regular":"a", "sensitive":"*****"}
t= "{\"regular\":\"a\",sensitive:b}"; //{"regular":"a", "sensitive":"b"}
r = t.replaceAll("(\\s*)\"?sensitive\"?\\s*:\\s*\"?b\"?\\s*", "$1\"sensitive\":\"*****\"");
System.out.println("output "+r); //output {"regular":"a","sensitive":"*****"}
DEMO: https://regex101.com/r/uHUhEl/1/
Upvotes: 1
Reputation: 336188
Depending on how malformed your "JSON" is, the following might work - if not, we need more test cases:
"sensitive"\s*:\s* # match "sensitive":
( # capture in group 1:
"[^"]*" # any quoted value
| # or
[^\s,{}"]* # any unquoted value, ending at a comma, brace or whitespace
) # end of group 1
In Java:
String resultString = subjectString.replaceAll(
"(?x)\"sensitive\"\\s*:\\s* # match \"sensitive\":\n" +
"( # capture in group 1:\n" +
" \"[^\"]*\" # any quoted value\n" +
"| # or\n" +
" [^\\s,{}\"]* # an unquoted value, ending at comma, brace or whitespace\n" +
") # end of group 1",
"\"sensitive\":\"******\"");
Test it live on regex101.com.
Upvotes: 4
Reputation: 36304
You can use positive lookbehind to achieve this :
public static void main(String[] args) {
String s = "{\"regular\":\"a\", \"sensitive\":\"b\"}";
String key = "sensitive";
String val = "****";
System.out.println(s.replaceAll("(?<=\"" + key + "\":\")(\\w+)", val));
key = "regular";
System.out.println(s.replaceAll("(?<=\"" + key + "\":\")(\\w+)", val));
}
O/P :
{"regular":"a", "sensitive":"****"}
{"regular":"****", "sensitive":"b"}
Upvotes: 3