如何检查String是否包含SimpleDateFormat中的日期并检索日期?

时间:2015-06-25 14:14:05

标签: java string date contains simpledateformat

到目前为止我的代码:

String string = "Temp_2014_09_19_01_00_00.csv"  
SimpleDateFormat format = new SimpleDateFormat("yyyy_MM_dd");

如何检查字符串是否包含日期?我该如何找回这个日期?任何方向?

1 个答案:

答案 0 :(得分:2)

以下是使用正则表达式执行所需操作的简单示例(您可能希望自己研究正则表达式):

public static void main(String[] args) throws FileNotFoundException, ParseException {
    String string = "Temp_2014_09_19_01_00_00.csv";
    SimpleDateFormat format = new SimpleDateFormat("yyyy_MM_dd");
    Pattern p = Pattern.compile("\\d\\d\\d\\d_\\d\\d_\\d\\d");
    Matcher m = p.matcher(string);
    Date tempDate = null;
    if(m.find())
    {
        tempDate = format.parse(m.group());
    }
    System.out.println("" + tempDate);
}

正则表达式查找4digits_2digits_2digits然后如果找到一个并尝试将其转换为日期,则需要匹配。如果找不到匹配项,则tempDate将为null。如果你想引入timestamp,你也可以这样做。