Trying to replace multi line string in java using replaceAll method but it's not working. Is there anything wrong with below logic?
String content=" \"get\" : {\n" +
" \"name\" : [ \"Test\" ],\n" +
" \"description\" : \"Test description to replace\",\n" +
" \"details\" : \"Test details\"";
String searchString=" \"name\" : [ \"Test\" ],\n" +
" \"description\" : \"Test description to replace\",";
String replaceString=" \"name\" : [ \"Actual\" ],\n" +
" \"description\" : \"Replaced description\",";
Tried below options and none of them worked-
Pattern.compile(searchString, Pattern.MULTILINE).matcher(content).replaceAll(replaceString);
Pattern.compile(searchString, Pattern.DOTALL).matcher(content).replaceAll(replaceString);
content = content.replaceAll(searchString, replaceString);
DISCLAIMER: You should not use regex to manipulate JSON or XML that have infinite nested content. Finite automate are not adapted to manipulate those data structures and you should use a JSON/XML parser instead.
This being said, purely for learning purpose, I will quickly fix your code.
1) Use either replace
instead of replaceAll
to avoid that your searchString
is interpreted as a regex:
String content=" \"get\" : {\n" +
" \"name\" : [ \"Test\" ],\n" +
" \"description\" : \"Test description to replace\",\n" +
" \"details\" : \"Test details\"";
String searchString=" \"name\" : [ \"Test\" ],\n" +
" \"description\" : \"Test description to replace\",";
String replaceString=" \"name\" : [ \"Actual\" ],\n" +
" \"description\" : \"Replaced description\",";
System.out.println(content.replace(searchString, replaceString));
output:
"get" : {
"name" : [ "Actual" ],
"description" : "Replaced description",
"details" : "Test details"
2) Or use replaceAll
but escape the brackets to avoid them being interpreted as a character class definition attempt.
String searchString=" \"name\" : \\[ \"Test\" \\],\n" +
" \"description\" : \"Test description to replace\",";
String replaceString=" \"name\" : [ \"Actual\" ],\n" +
" \"description\" : \"Replaced description\",";
System.out.println(content.replaceAll(searchString, replaceString));
output:
"get" : {
"name" : [ "Actual" ],
"description" : "Replaced description",
"details" : "Test details"
Link : How to parse JSON in Java
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.