替换Java中的多行字符串

时间:2019-04-02 06:42:12

标签: java regex java-8

尝试使用replaceAll方法替换java中的多行字符串,但是它不起作用。以下逻辑有什么问题吗?

    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\",";

尝试了以下选项,但没有一个起作用-

Pattern.compile(searchString, Pattern.MULTILINE).matcher(content).replaceAll(replaceString);

Pattern.compile(searchString, Pattern.DOTALL).matcher(content).replaceAll(replaceString);

content = content.replaceAll(searchString, replaceString);

1 个答案:

答案 0 :(得分:0)

  

免责声明::您不应使用正则表达式来处理具有无限嵌套内容的JSON或XML。有限的自动化方法不适用于处理这些数据结构,您应该使用JSON / XML解析器代替。

话虽如此,纯粹出于学习目的,我将快速修复您的代码。

1)使用replace而不是replaceAll来避免将您的searchString解释为正则表达式:

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));

输出:

  "get" : {
    "name" : [ "Actual" ],
    "description" : "Replaced description",
    "details" : "Test details"

2)或使用replaceAll,但不要使用方括号,以免将其解释为字符类定义尝试。

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));

输出:

  "get" : {
    "name" : [ "Actual" ],
    "description" : "Replaced description",
    "details" : "Test details"

链接How to parse JSON in Java

  • 您应该将json结构加载到对象中
  • 将该对象的属性值更改为新值
  • 再次以json格式导出