问题描述
我有一个包含文件名的列表,大致如下: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.
这篇关于从字符串中提取日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!