繁体   English   中英

替换java中的多行字符串

[英]replace multi-line string in 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);

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM