I hava one jsonString
String target = "[{"nickName":"andy","password":"wei","userword":"weitest32123"}]";
I wish to get
String target = "[{"nickName":"andy","password":"xxx","userword":"xxx"}]";
I want to use the java String method replaceall(regex,"xxx");
how do?
3 Answers 3
Try this.
String input = "[{\"nickName\":\"andy\",\"password\":\"wei\",\"userword\":\"weitest32123\"}]";
String output = input.replaceAll("(?<=\"(pass|user)word\":\")[^\"]+", "xxx");
System.out.println(output);
output:
[{"nickName":"andy","password":"xxx","userword":"xxx"}]
Comments
You can do it with the Positive Lookbehind regexp regex101.com:
public static void main(String... args) {
String str = "\"[{\"nickName\":\"andy\",\"password\":\"wei\",\"userword\":\"weitest32123\"}]\"";
System.out.println(maskPassword(str)); // "[{"nickName":"andy","password":"xxx","userword":"xxx"}]"
}
public static String maskPassword(String str) {
String regex = "(?<=\"(password|userword)\":)(\"[^\"]+\")";
return str.replaceAll(regex, "\"xxx\"");
}
P.S. I strongly recommend you not to do this with json string. This could follow a problem in the future. It's better to parse this json string into an object and then create json back with modification.
E.g. you can use a tool that I wrote gson-utils
Comments
This may seem like you're trying to parse some JSON. I'm not sure if casting it to object and then hiding values would be better approach.
But if you really need to do this way, this would be the solution
// You need this 2 imports
//import java.util.regex.Matcher;
//import java.util.regex.Pattern;
String text = "[{\"nickName\":\"andy\",\"password\":\"wei\",\"userword\":\"weitest32123\"}]";
Pattern pattern = Pattern.compile("\"(?<key>password|userword)\":\"(?<value>.*?)\"");
Matcher matcher = pattern.matcher(text);
String result = matcher.replaceAll("\"${key}\":\"xxx\"");
In Regex you need to specify all keys that you want to mask
passwordoruserwordattributes could contain escaped quote characters. Or characters such as[,{,:,,etcetera. Or extra fields could be added or ... other things that would make the regex fragile.)"userword"or"password". This is the problem with using regexes for parsing. The edge-cases are tricky to deal with ...