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

标签 java wildcard simpledateformat

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

我遇到了这个问题,我需要匹配文件名并从中提取日期,但我似乎找不到适合这种情况的正确方法。虽然我承认下面的场景对于文件名来说根本不切实际,但我不得不将它仍然作为“假设”包含在内。

场景

文件名:19882012ABCseptemberDEF03HIJ12KLM0156_249.zip,格式:yyyyMMMddhhmmss'_.zip'

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

我看到很多解析这个问题(例如确定正确的年份)。我希望你们能阐明一些想法,帮助我找到正确的方向。

最佳答案

据我所知,SimpleDateFormat 中没有 sunch 内容,但您可以使用正则表达式检查输入文件名是否匹配,以及它是否提取匹配的内容来创建您的日期。

这是一个快速的正则表达式,可以验证您的标准:

(.*?)([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

关于java - 使用支持通配符的 SimpleDateFormat 解析日期字符串(例如 *yyyy*MM*dd*hh*mm*ss),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12241320/

相关文章:

java - 显式置零

java - 错误 : unmappable character for encoding UTF8 during maven compilation

java - SimpleDateFormat 抛出 ParseException

java - 获取 "parse exception"

java - 将字符串解析为日期

java - HttpUrlConnection 读取分块响应

java - 可比和泛型

c# - 如何使用通配符搜索文件列表

python - 读取未知目录中的文件

java Runtime.getRunTime().exec 和通配符?