This question already has answers here:
Way to detect if String content is a DateTime - RegExp? [duplicate]
                                
                                    (3个答案)
                                
                        
                                4年前关闭。
            
                    
到目前为止,我的代码:

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


如何检查字符串是否包含日期?我如何获取该日期?有方向吗?

最佳答案

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

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,也可以这样做。

07-24 09:47
查看更多