Regex to match nested json objects

java, regex

Solution

Thanks to @Sanjay T. Sharma that pointed me to "brace matching" because I eventually got some understanding of greedy expressions and also thanks to others for saying initially what I shouldn't do. Fortunately it turned out it's OK to use greedy variant of expression

\\{\s*title.*\\}

because there is no non-JSON data between closing brackets.

Problem

I'm implementing some kind of parser and I need to locate and deserialize json object embedded into other semi-structured data. I used regexp: ``` \\{\\s*title.*?\\} ``` to locate object ``` {title:'Title'} ``` but it doesn't work with nested objects because expression matches only first found closing curly bracket. For ``` {title:'Title',{data:'Data'}} ``` it matches ``` {title:'Title',{data:'Data'} ``` so string becomes invalid for deserialization. I understand that there's a greedy business coming into account but I'm not familiar with regexps. Could you please help me to extend expression to consume all available closing curly brackets. Update: To be clear, this is an attempt to extract JSON data from semi-structured data like HTML+JS with embedded JSON. I'm using GSon JAVA lib to actually parse extracted JSON.

Original source

Related problems