【问题标题】:Regular expression for new Date object in JSONJSON中新日期对象的正则表达式
【发布时间】:2014-08-15 14:47:53
【问题描述】:

我被这个特殊的正则表达式困住了。我有以下内容:

"sampleDay": newDate(1402027200000)

并需要它以以下格式显示:1402027200000

到目前为止,我可以在 Java 中使用以下内容完全删除日期:

myDate = myDateJSON.replaceAll("newDate\\([^\\)]*\\)" ,"\" \"");

【问题讨论】:

    标签: java regex json date format


    【解决方案1】:

    您也可以使用捕获组,

    String str = "\"sampleDay\": newDate(1402027200000)";
    System.out.println(str.replaceAll(".*?newDate\\(([^\\)]*)\\).*", "$1")); // 1402027200000
    

    【讨论】:

      【解决方案2】:

      您只需要数字,然后使用 \D 替换所有非数字

      String str = "\"sampleDay\": newDate(1402027200000)";
      System.out.println(str.replaceAll("\\D+", ""));  // print 1402027200000
      

      或使用Character Classes or Character Sets 来否定使用[^\d] 的任何数字

      String str = "\"sampleDay\": newDate(1402027200000)";
      System.out.println(str.replaceAll("[^\\d]+", ""));
      

      阅读更多关于Java Pattern

      【讨论】:

        【解决方案3】:

        我会使用 SimpleDateFormat 将 JSON 日期转换为 Java 日期,处理转换问题,然后将其重新格式化为字符串(再次使用 SimpleDateFormat)

        String jsonDate = "1402027200000";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMDDHHmmss", Locale.ENGLISH);
        try {
          Date date = sdf.parse(jsonDate);
        } catch(ParseException e) {
          System.out.printf("%s is not parsable!%n", jsonDate);
          throw e; // Rethrow the exception.
        }
        String formattedDate = sdf.format(date); 
        

        在Java8中你可以使用DateTimeFormatter:

        String jsonDate = "1402027200000";
        DateTimeFormatter dtf = new DateTimeFormatter.ofPattern("yyyyMMDDHHmmss");
        try {
          LocalDate date = LocalDate.parse(jsonDate, dtf);
        
        } catch(DateTimeParseException e) {
          //Exception handling
          System.out.printf("%s is not parsable!%n", jsonDate);
          throw e; // Rethrow the exception.
        }
        String formattedDate = dtf.format(date); 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-12-17
          • 2020-08-11
          • 1970-01-01
          • 2012-03-08
          • 2014-04-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多