【问题标题】:replace multi-line string in java替换java中的多行字符串
【发布时间】:2019-04-02 06:42:11
【问题描述】:

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

【问题讨论】:

  • 我目前无法对此进行测试,但您肯定需要转义搜索字符串中的[ 括号(将它们更改为\\[)。也许这已经解决了它。
  • 您可以用\Q开头引用整个搜索字符串或调用Pattern.quote()
  • 使用这样的东西:String str = content.replaceAll("\\n","");
  • 由于您没有使用正则表达式,因此请使用简单的content = content.replace(searchString, replaceString); 或更复杂的content = Pattern .compile(searchString, Pattern.LITERAL).matcher(content).replaceAll(replaceString);。如果您想保留 compile 的结果并多次使用,后者是有意义的。然后,您会从准备工作中受益,例如幕后使用的 Boyer-Moore 算法。

标签: java regex java-8


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2015-03-06
    • 1970-01-01
    • 2017-02-24
    • 2023-02-23
    • 2015-12-23
    • 1970-01-01
    • 2015-05-01
    • 1970-01-01
    相关资源
    最近更新 更多