JSON中新Date对象的正则表达式

时间:2014-08-15 14:47:53

标签: java regex json date format

我坚持这个特殊的正则表达式。我有以下内容:

"sampleDay": newDate(1402027200000)

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

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

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

3 个答案:

答案 0 :(得分:1)

您也可以使用捕获组,

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

答案 1 :(得分:0)

您只需要数字,然后使用\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

答案 2 :(得分:0)

我会使用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);