[英]how to use Java to replace String?(regex)
我有一个 jsonString
String target = "[{"nickName":"andy","password":"wei","userword":"weitest32123"}]";
我希望得到
String target = "[{"nickName":"andy","password":"xxx","userword":"xxx"}]";
我想使用 java 字符串方法replaceall(regex,"xxx");
怎么办?
尝试这个。
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"}]
您可以使用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\"");
}
PS我强烈建议您不要使用 json 字符串执行此操作。 这可能会在将来出现问题。 最好将此 json 字符串解析为 object ,然后通过修改创建 json 。
例如,您可以使用我编写的工具gson-utils
这看起来好像您正在尝试解析一些 JSON。 我不确定是否将其转换为 object 然后隐藏值会是更好的方法。
但如果你真的需要这样做,这将是解决方案
// 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\"");
在正则表达式中,您需要指定要屏蔽的所有键
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.