Usman Rana
Usman Rana

Reputation: 2142

Regex.findAll is getting stucked somewhere when nested json text is passed and never returning response

I'm trying to find all json patterns/patches in a string if there exists any. For that I'm using val regex = "\\{(?:[^{}]*|\\{[^{}]*\\})*\\}".toRegex(). It works fine for simple jsons or upto 2 step nested json. But if json is i.e of 3 steps nested then regex.findAll(row) never returns anything and doesn't even throw in exception or finally block if I place inside a try/catch. Sample method is as following that is causing the problem:

private fun testRegex() {
    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 regex = "\\{(?:[^{}]*|\\{[^{}]*\\})*\\}".toRegex()
            val jsonMatches = regex.findAll(text)
            Log.d("json_matches", "jsonMatches= ${jsonMatches.count()}")
        } catch (e: Exception) {
            Log.d("json_matches", "exception: Never comes here")
        } finally {
            Log.d("json_matches", "finally: Never comes here")
        }
    }
}

What I want is to atleast throw some exception so we can handle it someother way. But it seems to be going in an infinite process, because finally is also not reachable for such text. Any ideas would be appreciable. Thanks

Upvotes: 0

Views: 29

Answers (0)

Related Questions