首页 > 解决方案 > 替换java中的多行字符串

问题描述

尝试使用 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);

标签: javaregexjava-8

解决方案


免责声明:您不应使用正则表达式来操作具有无限嵌套内容的 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"

链接如何在 Java 中解析 JSON

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

推荐阅读