使用支持通配符的SimpleDateFormat分析日期字符串(例如*yyyy*MM*dd*hh*MM*ss)



首先,我想知道是否有类似于SimpleDateFormat但支持通配符的现有库?如果没有,最好的方法是什么?

我遇到了这个问题,我需要从文件名中匹配和提取日期,但我似乎找不到适合这种情况的方法。虽然我承认下面的场景对于文件名来说根本不实用,但我不得不将其作为"假设"来包含。

场景

文件名:1982012BCseptemberDEF03HIJ12KLM0156_249.zip,模式yyyyMMMddhhmmss'_.zip’

  • 预计日期:2012年9月3日上午12:01:56
  • 分解版本:1988-2012-ABC-九月-DEF-03-HIJ-12-KLM-01-56-_249.zip

我在分析这一点时看到了很多问题(例如,确定正确的年份)。我希望你们能给我一些启示,帮助我走上正确的方向。

我不知道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

最新更新