在近期的文本決議程序中需要提取文本內的日期并規范格式,常用格式為“yyyy-MM-dd”。
由于寫法各異,無法用Date函式或SimpleDateFormat函式格式化,所以自己實作了一個方法。
經過測驗后凡是帶有分隔符的日期都能準確提取,現在不知道是否完善,代碼如下:
// 個位數的月份正則
static Pattern month = Pattern.compile("(?<=-)\\d(?=-)");
// 個位數的日/號正則
static Pattern day = Pattern.compile("(?<=-)\\d$");
public static String formatDate(String sourceDate) {
sourceDate = sourceDate.replaceAll("[年月../—]","-")
.replaceAll("[號日]$", "")
.replaceAll("[〇零OOo0]","0")
.replace("一","1")
.replace("二","2")
.replace("三","3")
.replace("四","4")
.replace("五","5")
.replace("六","6")
.replace("七","7")
.replace("八","8")
.replace("九","9")
.replace("廿","2");
// 十月的十轉換為 10
sourceDate = sourceDate.replaceAll("(?<=-)十(?=-)","10");
// 十幾的十轉換為 1
sourceDate = sourceDate.replaceAll("(?<=-)十(?=\\d)","1");
// 整十的十轉換為 0
sourceDate = sourceDate.replaceAll("(?<=\\d)十$","0");
// 幾十幾的十刪掉
sourceDate = sourceDate.replaceAll("(?<=\\d)十(?=\\d)","");
// 個位數月份前面加 0
Matcher matcher = month.matcher(sourceDate);
if (matcher.find()) {
sourceDate = sourceDate.substring(0,matcher.start()) + "0" + sourceDate.substring(matcher.start());
}
// 個位數日期前面加 0
matcher = day.matcher(sourceDate);
if (matcher.find()) {
sourceDate = sourceDate.substring(0,matcher.start()) + "0" + sourceDate.substring(matcher.start());
}
return sourceDate;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/270204.html
標籤:Java SE
