You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中替换字符串重复模式?IntelliJ下REST API字符串处理问题

问题解决方法

你的代码逻辑存在明显错误:getStringwithBracket的拼接写法错误(多了闭合括号)),且用整个剩余字符串去拼接匹配模式完全不符合需求,导致无法识别目标替换项。

针对你的需求,正确的处理逻辑应该是:

  • 移除所有出现的{"isSuccess":子串
  • 将块之间的分隔符(原字符串中}]}}[{"isSuccess":去掉{"isSuccess":后变成}]}}[)替换为对应格式的连接符

以下是修正后的代码:

public static String getResponseString(String response) {
    // 1. 全局移除所有{"isSuccess":子串,注意转义正则特殊字符
    String withoutIsSuccess = response.replaceAll("\\{\"isSuccess\":", "");
    // 2. 替换块之间的分隔符:把}]}}[替换为},[,匹配原始块结尾与下一个块开头的连接部分
    String actualResults = withoutIsSuccess.replaceAll("\\}\\}\\}\\]\\}\\[", "\\},\\[");
    return actualResults;
}

如果你的期望结果中还需要清理每个块末尾多余的闭合括号,可以再添加一步替换:

public static String getResponseString(String response) {
    String withoutIsSuccess = response.replaceAll("\\{\"isSuccess\":", "");
    // 先处理块间分隔符
    String temp = withoutIsSuccess.replaceAll("\\}\\}\\}\\]\\}\\[", "\\},\\[");
    // 移除每个块末尾多余的}}}
    String actualResults = temp.replaceAll("\\}\\}\\}([^\\}])", "$1");
    return actualResults;
}

关键注意点

  • 使用replaceAll时,正则中的特殊字符({、}、[、]等)必须用\\转义,否则会被当作正则语法解析
  • 要实现全局替换,直接使用replaceAll即可,无需拆分字符串后再拼接错误的匹配模式

内容的提问来源于stack exchange,提问作者Bubbles

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 18:20:05