我不知道有什么好东西,SimpleDateFormat
但是您可以做的是使用正则表达式检查输入文件名是否匹配,以及它是否提取匹配的内容以创建您的日期。
这是一个验证您的标准的快速正则表达式:
(.*?)([0-9]{4})([^0-9]*?)([a-z]+)(.*?)([0-9]{2})(.*?)([0-9]{2})(.*?)([0-9]{4})_([^.]+)[.]zip
这意味着(实际上并没有那么复杂)
(.*?) // anything
([0-9]{4}) // followed by 4 digits
([^0-9]*?) // followed by anything excepted digits
([a-z]+) // followed by a sequence of text in lowercase
(.*?) // followed by anything
([0-9]{2}) // until it finds 2 digits
(.*?) // followed by anything
([0-9]{2}) // until it finds 2 digits again
(.*?) // followed by anything
([0-9]{4}) // until if finds 4 consecutive digits
_([^.]+) // an underscore followed by anything except a dot '.'
[.]zip // the file extension
你可以在Java中使用它
String filename = "19882012ABCseptemberDEF03HIJ12KLM0156_249.zip";
String regex = "(.*?)([0-9]{4})([^0-9]*?)([a-z]+)(.*?)([0-9]{2})(.*?)([0-9]{2})(.*?)([0-9]{4})_([^.]+)[.]zip";
Matcher m = Pattern.compile(regex).matcher(filename);
if (m.matches()) {
// m.group(2); // the year
// m.group(4); // the month
// m.group(6); // the day
// m.group(8); // the hour
// m.group(10); // the minutes & seconds
String dateString = m.group(2) + "-" + m.group(4) + "-" + m.group(6) + " " + m.group(8) + m.group(10);
Date date = new SimpleDateFormat("yyyy-MMM-dd HHmmss").parse(dateString);
// here you go with your date
}
ideone 上的可运行示例:http: //ideone.com/GBDEJ
编辑:您可以通过删除您不关心的括号来避免匹配您不想要的内容。然后正则表达式变为.*?([0-9]{4})[^0-9]*?([a-z]+).*?([0-9]{2}).*?([0-9]{2}).*?([0-9]{4})_[^.]+[.]zip
,匹配组变为
group(1): the year
group(2): the month
group(3): the day
group(4): the hour
group(5): the minutes & secondes