Java如何提取文件名中的日期?

例如这段文件名:localhost_access_log.2017-07-24
我要提取出2017-07-24这个字符串
不要用2017前的小数点作为分割,可能文件名中还会有小数点存在

直接取后面10位的string就行了,反正时间日期都是固定长度。

@Test
public void test(){
String data="localhost_access_log.2017-07-24";
String substring = data.substring(21);
System.out.println(substring);
}
输出:2017-07-24

这个东西需要你自己根据格式来写方法,不出查串 拆分

    String str = "localhost_access_log.2017-07-24";

    String regex="\\d{4}-\\d{2}-\\d{2}";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(str);

    String result = null;
    if(matcher.find()){
        result = matcher.group();
    }

    System.out.println(result);

小数点分割为什么不行,只取最后一个小数点后的不就行了吗

localhost_access_log.2017-07-24
Java 字符串很容易处理,提取

这个和你文件里面有多个小数点有关系吗?
就像上面说的你可以split(".")之后,取最后一个l数组中en-1位置的字符串就是你要的时间

除非你时间中有小数点,这种方法那就不行了

其实你不说清文件名的格式,很难有个定论吧,就比如是不是日期一定出现在最后的位置,或者有多少个小数点,还有多少特殊符号等,文件名不确定提取方法自然就不确定了。