从字符串中提取日期 [英] Extracting dates from string

查看:660
本文介绍了从字符串中提取日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含文件名的列表,大致如下:Gadget1-010912000000-020912235959.csv,即它们包含两个日期,表示数据的时间间隔。



用户输入日期格式和文件格式:




  • 这种情况下的文件格式:* GADGET * - * DATE_FROM * - * DATE_TO * .csv

  • 这种情况下的日期格式:ddMMyyHHmmss



我想做的是以文件名和日期格式提取出文件名中的三个值。



我的问题是:由于日期格式有差异(小时,分,秒)被一个冒号分开,以点为单位...)我不太清楚如何创建一个拟合的正则表达式。

解决方案

您可以使用正则表达式删除非数字字符,然后解析值。

  DateFormat dateFormat = new SimpleDateFormat (ddMMyyHHmmss); 

String [] fileNameDetails =(Gadget1-010912000000-020912235959)。split( - );

/ *捕获所有非数字字符并将其删除。如果不存在维护原始字符串* /
String date = fileNameDetails [1] .replaceAll([^ 0-9],);

try {
dateFormat.parse(fileNameDetails [1]);
} catch(ParseException e){
}

希望它有帮助。 / p>

I have a list with file names that look roughly like this: Gadget1-010912000000-020912235959.csv, i.e. they contain two dates indicating the timespan of their data.

The user enters a date format and a file format:

  • File Format in this case: *GADGET*-*DATE_FROM*-*DATE_TO*.csv
  • Date format in this case: ddMMyyHHmmss

What I want to do is extracting the three values out of the file name with the given file and date format.

My problem is: Since the date format can differ heavily (hours, minutes and seconds can be seperated by a colon, dates by a dot,...) I don't quite know how to create a fitting regular expression.

解决方案

You can use a regular expression to remove non digits characters, and then parse value.

DateFormat dateFormat = new SimpleDateFormat("ddMMyyHHmmss");

String[] fileNameDetails = ("Gadget1-010912000000-020912235959").split("-");

/*Catch All non digit characters and removes it. If non exists maintains original string*/
String date = fileNameDetails[1].replaceAll("[^0-9]", "");

try{
    dateFormat.parse(fileNameDetails[1]);
}catch (ParseException e) {
}

Hope it helps.

这篇关于从字符串中提取日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆