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() ;
添加回答
舉報