【问题标题】:RegEx to replace to given date with the current date正则表达式用当前日期替换给定日期
【发布时间】:2020-06-16 09:03:45
【问题描述】:

我已将 json 反序列化为字符串变量,我想在所有出现的情况下将下面的变量更新为当前日期

"buyDate":"2019-04-09T13:21:00.866Z",

String result = content.replaceAll("(\"buyDate\":\"(\\d{4}-\\d{2}-\\d{2}\\.*$)\")", "\"buyDate\":" + LocalDate.now().toString() + "\"");

但是上面的逻辑是失败的。有人可以提出解决方案吗?

【问题讨论】:

  • 我认为 String.replaceAll 在处理 JSON 数据时并不是最好的主意...考虑将 JSON 反序列化为对象、操作它们的值并重写 JSON 文件。

标签: java json regex replace


【解决方案1】:

我建议使用parsers 来解析和修改动态 JSON 数据。但是,如果 JSON 是静态的,并且您想使用正则表达式来实现您的结果;那么你的正则表达式是非常正确的(虽然它可以被压缩。见答案)。您只需要使用LocalDateTime 实例而不是LocalDate 实例。类似的东西;

// Sample code. Please manipulate according to your requirements.
import java.time.*;

public class Main
{
    public static void main(String[] args) {
        // Sample test String
        String content = "\"buyDate\":\"2019-04-09T13:21:00.866Z\"";
       // String result = content.replaceAll("(\"buyDate\":\"(\\d{4}-\\d{2}-\\d{2}.*)\")", "\"buyDate\":\"" 
        //+ LocalDateTime.now().toString() + "Z\"");
// COMPACTED REGEX
        String result = content.replaceAll("(\"buyDate\":\".*?\"", "\"buyDate\":\"" 
        + LocalDateTime.now().toString() + "Z\"");
        System.out.println(result);
    }
}
// Outputs: "buyDate":"2020-06-16T09:33:38.276Z" a.t. online IDE's local time.

您可以在here.找到上述代码的示例运行


如果您只想替换保留时间和零小时格式的日期值(尽管我认为没有任何实际理由这样做);那么你可以试试这个:

import java.time.*;
import java.time.format.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Main
{
    public static void main(String[] args) {
        LocalDate dt = LocalDate.now();
        final String regex = "\"buyDate\":\"(\\d{4}-\\d{2}-\\d{2})T";
        final String string = "\"buyDate\":\"2019-04-09T13:21:00.866Z\"";
        DateTimeFormatter formatDateToday=DateTimeFormatter.ofPattern("YYYY-MM-dd");
        final String subst = "\"buyDate\":\""+ dt.format(formatDateToday) +"T";

        final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
        final Matcher matcher = pattern.matcher(string);

        // The substituted value will be contained in the result variable
        final String result = matcher.replaceAll(subst);
        System.out.println(result);
    }
}
  • 我使用DateTimeFormatter 类来格式化日期。
  • 我使用PatternMatcher 类仅匹配给定JSON 字符串中的日期。

以上代码的运行示例可以在here.找到

【讨论】:

    【解决方案2】:

    为什么在正则表达式中有$,然后是\"? 这足以"(\"buyDate\":\"(\\d{4}-\\d{2}-\\d{2}.*)\")"

    你的最终代码会是这样的

    String result = content.replaceAll("(\"buyDate\":\"(\\d{4}-\\d{2}-\\d{2}.*)\")", "\"buyDate\":" + LocalDate.now().toString() + "\"");
    

    您应该使用java.time 包类进行更简洁的操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多