-4

I have a Json file containing text as such:

{
    title1: {
        x: "abc",
        y: "def"
    } ,

    title2:{
        x: "{{abc}}",
        y: "{{def}}"
    },
}

I want to first get the title1 title2 ,... groups. And after that, for each group, I want to get the x:..., y:... parts. I try to do this in two steps. For the first step, I used the following regexp:

[\s\S]*:\s*{(((?!}\s*,)[\s\S])*)

I am trying to say that find : followed by optional white space and then {. Then, continue until you see } followed by optional whitespace and ,. But it finds the whole text as a match instead of title1 and title2 parts separately. What is wrong with it?

John L.
  • 1,825
  • 5
  • 18
  • 45
  • 2
    It might be easier to write an own JSON parser. Or even easier to use an existing one. Any particular reason you are trying to do it with regular expressions? – Marvin Sep 14 '19 at 21:47
  • 2
    A couple quick notes. First, the text in your question is _not_ JSON. Second, assuming you do get JSON, you _can't_ parse JSON with a regular expression (due to arbitrarily nested constructs) so you should use your language's built in JSON parser. All major languages have them. Cheers. – Ray Toal Sep 14 '19 at 21:48

1 Answers1

1

Maybe, this expression,

(\S+):\s*{\s*(((\S+):\s*"{*([^"{}]*)}*"\s*,?\s*)+)}

Demo 1

or:

(\S+):\s*{\s*(((\S+):\s*"{{0,2}([^"{}]*)}{0,2}"\s*,?\s*)+)}

Demo 2

with bounded quantifier might be somewhat closer to what you have in mind.


If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


Emma
  • 27,428
  • 11
  • 44
  • 69