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

Regex.findAll处理多层嵌套JSON时卡住无响应且不抛异常问题

问题原因分析

你的正则表达式存在灾难性回溯问题。当处理3层及以上嵌套的JSON时,正则分支(?:[^{}]*|\\{[^{}]*\\})*会生成指数级的匹配路径,导致CPU持续高负载,程序陷入无限循环——既不会返回匹配结果,也不会抛出异常,因此finally块无法执行。

解决思路

1. 用栈匹配成对括号(推荐)

正则天生不适合处理递归嵌套结构,改用栈来追踪{和}的匹配关系,能高效处理任意层数的嵌套,且不会出现卡顿:

private fun findJsonFragments(text: String): List<String> {
    val fragments = mutableListOf<String>()
    val stack = ArrayDeque<Int>()
    
    text.forEachIndexed { index, char ->
        when (char) {
            '{' -> stack.push(index)
            '}' -> {
                if (stack.isNotEmpty()) {
                    val startIndex = stack.pop()
                    // 栈为空时,说明找到了一个完整的顶级JSON结构
                    if (stack.isEmpty()) {
                        fragments.add(text.substring(startIndex, index + 1))
                    }
                }
            }
        }
    }
    return fragments
}

调用示例:

private fun testJsonExtraction() {
    lifecycleScope.launch(ioDispatcher) {
        try {
            val text = "{\"message\":\"Bad Gateway\",\"code\":502,\"errors\":[{\"message\":\"Failed to get configuration of type: ae.network.transaction.domain.config.FeatureToggleResponse\",\"localizedMessage\":\"{error.processing.configFetchError}\",\"errorCode\":\"configFetchError\",\"domain\":\"processing\"}]}"
            val jsonFragments = findJsonFragments(text)
            Log.d("json_matches", "jsonMatches= ${jsonFragments.size}")
            jsonFragments.forEach { Log.d("json_fragment", it) }
        } catch (e: Exception) {
            Log.d("json_matches", "exception: ${e.message}")
        } finally {
            Log.d("json_matches", "finally: Executed")
        }
    }
}

2. 使用专门的JSON解析库

如果需要进一步处理JSON内容,直接用Gson、Moshi或kotlinx-serialization等专业库解析,比正则或栈的方式更可靠:

  • 若目标是提取完整JSON结构:直接将字符串传入解析器,验证并解析;
  • 若目标是从混合文本中提取JSON片段:先用栈定位片段,再交给解析库处理内容。

3. 避免用正则处理嵌套JSON

标准Java/Kotlin正则引擎不支持递归匹配,任何试图用正则处理多层嵌套JSON的方案,都可能因回溯问题导致性能灾难,不推荐使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 14:22:09