Search code examples
javaregexstringreplaceregexp-replace

Append using Regex Replace with repeating pattern


I have following pattern which I need to append/replace in my Java program.

Example string:

1: {\"values" : ["AnyValue1", "TestValue", "Dummy", "SomeValue"], "key" : "value"}

2: {\"otherValue\": \"AnyValue1\", \n" + "\"values\" : [\"AnyValue1\", \"TestValue\", \"Dummy\", \"SomeValue\"], \"key\" : \"value\"}

There can be N number of values in this value array.

I need to append all values with _val. However, only the values inside values should be appended with _val.

Output 1: { "values" : ["AnyValue1_val", "TestValue_val", "Dummy_val", "SomeValue_val"], "key" : "value" }

Output 2: {"otherValue": "AnyValue1", 
          "values" : ["AnyValue1_val", "TestValue_val", "Dummy_val", "SomeValue_val"], "key" : "value"}

I was wondering if somehow I can use regex Replace instead of going through loops?

Content are in a String:

String content = "{ \"values\" : [\"AnyValue1\", \"TestValue\", \"Dummy\", \"SomeValue\"], \"key\" : \"value\" }";

Solution

  • Alternative:

    public static void main(String[] args) {
        String input = "{ \"values\" : [\"AnyValue1\", \"TestValue\", \"Dummy\", \"SomeValue\"], \"key\" : \"value\" }";
    
        Matcher matcher = Pattern.compile("(.*?\\[)(.*?)(\\].*)").matcher(input);
        if(matcher.find()) {
            String val = matcher.group(2).replaceAll("(\\w+)", "$1_val");
            System.out.println(matcher.group(1) + val + matcher.group(3));
        }
    }
    

    Output:

    { "values" : ["AnyValue1_val", "TestValue_val", "Dummy_val", "SomeValue_val"], "key" : "value" }