0

Hiho,

I have a json string with the following structure:

{
   "version": "1.0.0",
   "dependencies": {
      "version": "1.0.0"
   }
}

It can also look like this:

{
   "dependencies": {
      "version": "1.0.0"
   },
   "version": "1.0.0"
}

Or like this:

{ "version": "1.0.0", "dependencies": { "version": "1.0.0" } }

Or like this:

{ "dependencies": { "version": "1.0.0" }, "version": "1.0.0" }

As can be seen, the string contains 2 times the name "version" with the value "1.0.0". One time on 'top' level of the json structure, and one time one level deeper.

  • Before/behind the name "version" can be other name/value pairs.
  • The name "version" can occur only 1 time on top level.
  • The name "version" can occur multiple times in deeper levels.

Now I want to replace the value "1.0.0" with another value, but only the top level value! I tried to define a regular expression for this, but failed so far.

I'm starting to wonder if it's even possible to define such an expression. The underlying problem seems to be that the first hit of the name is not necessarily the top-level key (see examples 2 and 4).

It would be really nice if someone could help me! :)

1 Answers1

1

This may not work depending on your Java version (that's the tag you used) as it requires the use of non-fixed width Lookaheads and Lookbehinds, but this regex should be usable in later versions of Java or JavaScript.

(?:(?<!(?:[\s\S]*\{[\s\S]*){2,})(?<="version" *: *")([\d\.]*)(?=")|(?<="version" *: *")([\d\.]*)(?=")(?!(?:[\s\S]*\}[\s\S]*){2,}))

You can test it by yourself and see how it works in the following link: https://regex101.com/r/6Q3KXQ/1

Odd One Out
  • 156
  • 9