【问题标题】:Java Replace All Regular ExpressionJava替换所有正则表达式
【发布时间】:2014-08-08 20:41:30
【问题描述】:

我正在尝试在java中编写一个replaceAll,它可以将json替换为一个数组而不是一个对象,这是我的意思的一个例子:

test:[{\"asdf\":\"asasdd\"}]

我的目标是将测试对象中的所有 } 替换为数组但不影响任何其他 }

(我使用的 json 是有效的(与下面的 json 不同)但我一直在用下面的字符串进行测试,因为我希望它会得到相同的结果,而且要短得多)

String test = "[asdfasdf}test:{\"asdf\":\"asasdd\"}.sdfasdfsadfsdf, test:{\"asdf\":\"asasdd\"}sdfsdf } ";

//期望的结果

String test = "[asdfasdf}test:[{\"asdf\":\"asasdd\"}].sdfasdfsadfsdf, test:[{\"asdf\":\"asasdd\"}]sdfsdf } ";


System.out.println(test.replaceAll("(?<=[test:{])}", "}]")); // 

所以作为旁注,我想指出为什么我发现这个问题很重要,这是因为一个糟糕的供应商将 json 作为一个对象而不是一个数组返回,如果它没有一个以上的结果.因此,它破坏了我的 json 类解析器

【问题讨论】:

  • 使用正确的 JSON 解析 API。
  • 据我所知,每个 Json Parsing Api 都不起作用,这是因为供应商不会在数组中返回结果,即使它通常是一个数组
  • 想要的输出是什么?
  • 你知道有哪些库可以将一个对象隐式转换为一个数组吗?
  • String test = "[asdfasdf}test:[{\"asdf\":\"asasdd\"}].sdfasdfsadfsdf, test:[{\"asdf\":\"asasdd\" }]sdfsdf } ";

标签: java regex regex-lookarounds


【解决方案1】:

这应该可行:

(?<=\btest:){[^}]*}

这里是DEMO

示例代码:

String input  = "[asdfasdf}test:{\"asdf\":\"asasdd\"}.sdfasdfsadfsdf, test:{\"asdf\":\"asasdd\"}sdfsdf } ";
System.out.println(input.replaceAll("(?<=\\btest:)\\{[^}]*\\}","[$0]"));

模式说明:

  (?<=                     look behind to see if there is:
    \b                       the word boundary
    test:                    'test:'
  )                        end of look-behind
  {                        '{'
  [^}]*                    any character except: '}' (0 or more times)
  }                        '}'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 1970-01-01
    • 2010-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多