Home > Enterprise >  Regex to replace values inside the first curly braces after a specific keyword
Regex to replace values inside the first curly braces after a specific keyword

Time:11-09

I have an input string and I would like to replace the values inside the first curly braces (including the curly braces) after a specific keyword.

For example in this example I would like to replace the values inside the curly braces which comes after Honda.

[{brand:”Toyota”, model:”Corolla”}, 
{brand:”BMW”, model:”X3”}, 
{brand:”Honda”, model:”{year:2022, name:Accord}”}]

So the end result will be something like:

[{brand:”Toyota”, model:”Corolla”}, 
{brand:”BMW”, model:”X3”}, 
{brand:”Honda”, model:”Civic”}]

It looks like when using Java I can use replaceAll method to utilize a regex expression but I couldn't figure what should be the regex expression for this use case.

I tried to create a regex like this one below but result was wrong

String output = input.replaceAll("Honda.*(?<=\\{).*?(?=\\})","Civic");
[{brand:”Toyota”, model:”Corolla”},
{brand:”BMW”, model:”X3”},
{brand:”Civic}”}]

CodePudding user response:

Look-behinds are problematic because (in Java) they must be fixed-length. An alternative is to capture the prefix (the brand) and then repeat that as $1 in the replacement string.

This regex will capture the brand. Notice the surrounding parentheses.

(\{brand:"Honda", model:")

And this will match the model (excluding the trailing quote):

[^"]*

Concatenate the two parts. Put them in a string literal, escaping every \ and ":

"(\\{brand:\"Honda\", model:\")[^\"]*"

Optionally, add \\s* to make it robust against arbitrary whitespace:

"(\\{\\s*brand\\s*:\\s*\"Honda\"\\s*,\\s*model\\s*:\\s*\")[^\"]*"

Make sure the replacement string starts with $1:

"$1Civic"

Working example:

class Main
{
   public static void main(String[] args)
   {
      String input = "[{brand:\"Honda\", model:\"{year:2022, name:Accord}\"}]";
      System.out.println(input);
      String output = input.replaceAll(
         "(\\{\\s*brand\\s*:\\s*\"Honda\"\\s*,\\s*model\\s*:\\s*\")[^\"]*",
         "$1Civic");
      System.out.println(output);
   }
}

Output:

[{brand:"Honda", model:"{year:2022, name:Accord}"}]
[{brand:"Honda", model:"Civic"}]
  • Related