2 回答

TA贡献1797条经验 获得超6个赞
是的,您可以使用下面的正则表达式来检索日期。
Pattern p = Pattern.compile("(\\d{4}-\\d{2}-\\d{2})");
Matcher m = p.matcher("2017-01-31 01:33:30 random text log message x");
if (m.find()) {
System.out.println(m.group(1)); //print out the date
}

TA贡献1802条经验 获得超6个赞
正则表达式是矫枉过正
这里不需要棘手的正则表达式匹配。只需将日期时间文本解析为日期时间对象。
java.time
在您的示例中,仅使用了两种格式。所以尝试使用现代的java.time类来解析每一个。它们是相似的,一个是日期优先,另一个是时间优先。
DateTimeFormatter fDateTime = DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" ) ;
DateTimeFormatter fTimeDate = DateTimeFormatter.ofPattern( "HH:mm:ss uuuu-MM-dd" ) ;
首先,从字符串中提取前 19 个字符,只关注日期时间数据。
解析,为DateTimeParseException.
LocalDateTime ldt = null ;
try{
if( Objects.isNull( ldt ) {
LocalDateTime ldt = LocalDateTime.parse( input , fDateTime ) ;
}
} catch ( DateTimeParseException e ) {
// Swallow this exception in this case.
}
try{
if( Objects.isNull( ldt ) {
LocalDateTime ldt = LocalDateTime.parse( input , fTimeDate ) ;
}
} catch ( DateTimeParseException e ) {
// Swallow this exception in this case.
}
// If still null at this point, then neither format above matched the input.
if( Objects.isNull( ldt ) {
// TODO: Deal with error condition, where we encountered data in unexpected format.
}
如果您想要没有时间的仅日期,请提取一个LocalDate对象。
LocalDate ld = ldt.toLocalDate() ;
添加回答
举报