周梦康 发表于 2022-04-25 59 次浏览

前几日因为日志输出量大,但是很多时候又还想用日志来做兜底逻辑的查询,所以想在异步事件监听逻辑里去做字符串截取,比如有这样一个字符串

{
    "a": 123456,
    "b": "abcdefgabcdefgabcdefgabcdefgabcdefgabcdefg",
    "c": "abcdefgabcdefgabcdefgabcdefgabcdefgabcdefg",
    "message": "OK",
    "requestId": "0b89205b16508538498111994d2783",
    "success": true
}

目标值

{
    "a": 123456,
    "b": "abcdefgabcdefgabcdefgabcdefgabcde...",
    "c": "abcdefgabcdefgabcdefgabcdefgabcde...",
    "message": "OK",
    "requestId": "0b89205b16508538498111994d2783",
    "success": true
}

如果用正则简单处理的情况下,先匹配到所有的值中过长且为字符串的,大概就是这样一个正则:\"([^\"]+)\",(不够严谨)

这时候我就想到了 preg_replace_callback,但是在 java 里怎么都没找到,然后 stackoverflow 给了我答案

https://stackoverflow.com/questions/375420/java-equivalent-to-phps-preg-replace-callback

java8 也不是不能写出来,只是要自己写一段循环处理,重点是Matcher.appendReplacement

String jsonString = "{\"a\":123456,\"b\":\"abcdefgabcdefgabcdefgabcdefgabcdefgabcdefg\",\"c\":\"abcdefgabcdefgabcdefgabcdefgabcdefgabcdefg\",\"message\":\"OK\",\"requestId\":\"0b89205b16508538498111994d2783\",\"success\":true}";

StringBuffer resultString = new StringBuffer();
Pattern regex = Pattern.compile(":\"([^\"]+)\",");
Matcher regexMatcher = regex.matcher(jsonString);
while (regexMatcher.find()) {
    String matchString = regexMatcher.group(0);
    if (matchString.length() > 36) {
        matchString = matchString.substring(0,35) + "...\",";
    }
    regexMatcher.appendReplacement(resultString, matchString);
}
regexMatcher.appendTail(resultString);

System.out.println(resultString);

相比之下,PHP 就更为亲切,早在 PHP4 的时代就为开发者做了封装,所以如果你是一个小作坊呢,PHP 很多时候还是挺香的。
https://www.php.net/manual/zh/function.preg-replace-callback.php

发现 Java9 也补上了这个功能
https://docs.oracle.com/javase/10/docs/api/java/util/regex/Matcher.html#replaceAll(java.util.function.Function)

👇 下面是我的公众号,高质量的博文我会第一时间同步到公众号,给个关注吧!

评论列表