【问题标题】:Java Json String extract number and replace specific textJava Json String 提取数字并替换特定文本
【发布时间】:2019-07-05 17:23:30
【问题描述】:

我有一个 json 格式的文本文件,我想将 NumberInt(x) 替换为数字 x

在文本文件中,有一个 json 格式的记录/数据,其中有一个字段 workYear: NumberInt(2010) 作为示例。

我想通过删除 NumberInt() 将其替换为 workYear: 2010。 这个NumberInt(x) 位于文本文件中的任何位置,我想将其全部替换为它的编号。

我可以搜索所有出现的这个,但我不知道如何用数字值替换它。

String json = <json-file-content>

String sPattern = "NumberInt\\([0-9]+\\)";
Pattern pattern = Pattern.compile(sPattern);
Matcher matcher = pattern.matcher(json);

while (matcher.find()) {
    String s = matcher.group(0);
    int workYear = Integer.parseInt(s.replaceAll("[^0-9]", ""));
    System.out.println(workYear);
}

我想用数字值 int json 字符串替换所有 NumberInt(x)... 然后我将更新文本文件(json 文件)。

谢谢!

【问题讨论】:

    标签: java json regex


    【解决方案1】:

    以下应该可以工作。您需要捕获令牌。

        String json = "workYear:NumberInt(2010) workYear:NumberInt(2011)";
        String sPattern = "NumberInt\\(([0-9]+)\\)";
        Pattern pattern = Pattern.compile(sPattern);
        Matcher matcher = pattern.matcher(json);
    
        List<String> numbers = new ArrayList<>();
        while (matcher.find()) {
            String s = matcher.group(1);
            numbers.add(s);
        }
        for (String number: numbers) {
    
            json = json.replaceAll(String.format("NumberInt\\(%s\\)", number), number);
        }
        System.out.println(json);
    

    【讨论】:

      【解决方案2】:

      您可以使用StringBuilder 构建输出,如下所示, 请参阅appendReplacement 的 JavaDoc,了解其工作原理。

          String s = "workYear: NumberInt(2010)\nworkYear: NumberInt(2012)";
          String sPattern = "NumberInt\\([0-9]+\\)";
          Pattern pattern = Pattern.compile(sPattern);
          Matcher matcher = pattern.matcher(s);
      
          StringBuilder sb = new StringBuilder();
      
          while (matcher.find()) {
              String s2 = matcher.group(0);
              int workYear = Integer.parseInt(s2.replaceAll("[^0-9]", ""));
              matcher.appendReplacement(sb, String.valueOf(workYear));
          }
          matcher.appendTail(sb);
      
          String result = sb.toString();
      

      【讨论】:

      • 这似乎有效,但它没有使用 StringBuilder... 只有 StringBuffer。此外,它停在第 75439 行,仍在检查为什么停在那里,但没有出现任何错误。
      • 是最后一行吗?我添加了matcher.appendTail(sb); 以将任何剩余的文本添加到 Builder/Buffer 中。此外,如果输入非常大,您可以按行拆分并执行此操作并合并行。
      猜你喜欢
      • 1970-01-01
      • 2019-01-23
      • 2014-06-21
      • 2021-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-06
      • 1970-01-01
      相关资源
      最近更新 更多