繁体   English   中英

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

[英]Parsing date string using SimpleDateFormat with Wildcard support (e.g. *yyyy*MM*dd*hh*mm*ss)

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

我有这个问题,我需要匹配并从文件名中提取日期,但我似乎无法找到适合这种情况的方法。 虽然我承认下面的场景对于文件名来说根本不实用,但我必须将其作为“WHAT IF”包含在内。

脚本

文件名 :19882012ABCseptemberDEF03HIJ12KLM0156_249.zip, 模式yyyy MMM dd hh mmss'_ .zip'

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

我看到解决这个问题的很多问题(例如确定正确的年份)。 我希望你们能够解决一些问题并帮助我找到正确的方向。

我在SimpleDateFormat没有sunch的东西,但是如果输入文件名匹配,你可以做的是检查正则表达式,如果它确实提取匹配的东西来创建你的日期。

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

(.*?)([0-9]{4})([^0-9]*?)([az]+)(.*?)([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上的Runnable示例: http ://ideone.com/GBDEJ

编辑:你可以通过删除你不关心的括号来避免匹配你不想要的东西。 然后正则表达式变为.*?([0-9]{4})[^0-9]*?([az]+).*?([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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM