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

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

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

脚本

文件名:19882012ABCseptemberDEF03HIJ12KLM0156_249.zip,模式:yyyyMMMddhhmmss’_.zip’

>预计日期:2012年9月3日上午12:01:56

>细分版本:1988-2012-ABC-se-9-9-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

}

编辑:

你可以通过删除你不关心的括号来避免匹配你不想要的东西.然后正则表达式变为.*?([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

标签:java,simpledateformat,wildcard

来源: https://codeday.me/bug/20190901/1786067.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值