Map<String, Object> params = new HashMap<>(); params.put("password", "${nacos.password:}"); params.put("userName", "张某"); String paramStr = JSON.toJSONString(params); Pattern OTHER_PATTERN = Pattern.compile("(password)(=|=\\[|\\\":\\\"|:|:|=').*?(?>(\\\"|\\]|}|,|&|='))", Pattern.CASE_INSENSITIVE); Matcher otherPatternMatcher = OTHER_PATTERN.matcher(paramStr); while (otherPatternMatcher.find()) { String findStr=otherPatternMatcher.group(); String replaceContext = otherPatternMatcher.replaceAll("$1$2********"); System.out.println(paramStr.replaceAll(findStr, replaceContext)); }
提示报错:
这是因为replaceAll使用了正则匹配,导致有些字符如:$、/、{ 等符号转义,使用replace就好了
输出正确结果: