How to replace repetitive pattern in a string in Java?

93 Views Asked by At

I have intelliJ running with Java/REST API and having trouble removing and replacing string in a certain format.

Response string :

{"isSuccess":[{"frequency":}]}]}}{"isSuccess":[{"frequency":}]}]}}{"isSuccess":<testData>[{"frequency":<testData>}]}]}}

Expected string :

[{"frequency":}]},{"frequency":<testData>}]},{"frequency":<testData>}}]}]}}

Actual String :

[{"frequency":<testData>}]}]}}[{"frequency":<testData>}]}]}}[{"frequency":"<testData>}]}]}}

Code :

public static String getResponseString(String response){
        String getIDErrorCodeString = response.split("\\[")[0];                 
        String getStringWithoutIDErrorCode = response.replaceAll(Pattern.quote(getIDErrorCodeString), "");
        String getStringwithBracket = "}]}]" + getStringWithoutIDErrorCode + "}}[{";

        String actualResults = getStringWithoutIDErrorCode.replaceAll(Pattern.quote(getStringwithBracket), ",");

        return actualResults;
}

The original string had the }}[{ in the beginning of the line which got removed in the actual results but still pattern is not recognizing and finding the correct string to replace not just in the beginning but in the entire string. Anyone knows how to do this?

3

There are 3 best solutions below

0
On BEST ANSWER

It was very simple than I wrote originally,

public static String getResponseString(String response){
        String getIDErrorCodeString = response.split("\\[")[0];                  
        
        String getStringWithoutIDErrorCode = response.replaceAll(Pattern.quote(getIDErrorCodeString), "");
        String actualResults = getStringWithoutIDErrorCode.replaceAll("]}}\\[", ",");

    return actualResults;
0
On

Start by removing all occurrences of {"isSuccess":<testData>.

s = s.replace("{\"isSuccess\":<testData>", "");

Then, replace ]}}[, with ,.

s = s.replace("]}}[", ",");

And finally, insert a }, at n − 6.

s = s.substring(0, s.length() - 6) + '}' + s.substring(s.length() - 6);

Output

[{"frequency":<testData>}]},{"frequency":<testData>}]},{"frequency":<testData>}}]}]}}
5
On
public static String getResponseString(String response){

  String getIDErrorCodeString = response.split("\\[")[0];
  
  String getStringWithoutIDErrorCode = response.replaceAll(Pattern.quote(getIDErrorCodeString), "");

  String getStringwithBracket = "}]}]" + getStringWithoutIDErrorCode + "}}[{";

  String pattern = Pattern.quote(getStringwithBracket);
  String actualResults = getStringWithoutIDErrorCode.replaceAll(pattern, ",", Pattern.MULTILINE);

  return actualResults;

}

try using Pattern.quote() to escape the pattern string for regex and then Add the Pattern.MULTILINE flag so ^ and $ match start/end of each line after this use the g flag in the regex to replace all occurrences This will do a global regex replace to replace that pattern on each line.

-- Hope this helps