Shalaj
Shalaj

Reputation: 591

find whole json element using regex

I have a json below

{"name":"abc","config":{"key":1,"value":"one","detail":{"message": "testing"}}}

I need to get the whole config element that is "config":{"key":1,"value":"one","detail":{"message": "testing"}} using regex , i dont want to use any json parser, the config can contains any number of nested elements

I tried to use regex pattern - "config":{.*} but it is fetching till last } as it is greedy

any help is much appreciated

Upvotes: 0

Views: 100

Answers (2)

jmoney
jmoney

Reputation: 528

Ok. I was able to get a working solution, however it take two regexes to complete.

First step, grab everything after "config". Use capture group 1's contents:

"config":({.*})

Demo of Regex 1

Second step, use recursive regex to match balanced constructs, checkout more on this here in the "balanced constructs section". It uses recursion to find the closing curly brace that corresponds to the opening curly brace after "config":. Use match 1's contents:

{(?>[^{}]|(?R))*}

Demo of Regex 2

Upvotes: 1

Code Maniac
Code Maniac

Reputation: 37755

You can use this

"config":[\s\S]+?}(?=[,}])}

Here [\s\S]+? will match (lazy mode) everything followed by } or ,

Demo

Upvotes: 2

Related Questions