【发布时间】:2021-07-11 21:49:23
【问题描述】:
拜托,你能帮我解决这个问题吗?我已尝试实施以下解决方案,但均无效。
问题:
我必须将 CSV 文件中的所有字符串日期标准化为 YYYY-MM-DD HH: MM: SS:
2021-01-03 12:15:33.12365478 -> 2021-01-03 12:15:33
2021-01-03 -> 2021-01-03 00:00:00
输入文件:
OP|VALUE1|VALUE2|DATE
I |123 | ABC | 2021-01-03 12:15:33.12365478
I |123 | ABC | 2021-01-03 12:15:21
I |123 | ABC | 2021-01-03 12:15:12
I |123 | ABC | 2021-01-03
I |123 | ABC | 2021-01-03 12:15:33.12365478
希望输出文件:
OP|VALUE1|VALUE2|DATE
I |123 | ABC | 2021-01-03 12:15:33
I |123 | ABC | 2021-01-03 12:15:21
I |123 | ABC | 2021-01-03 12:15:12
I |123 | ABC | 2021-01-03 00:00:00
I |123 | ABC | 2021-01-03 12:15:33
每个文件大小约为 104MB。 我想到的解决方案:
备选方案 1:
public static String setDataCleaner(String in) {
String stringFinal = "";
for(String i: in.split("\\|")){
if(i.matches("[0-9]{4}-[0-9]{2}-[0-9]{2}")) {
stringFinal += i+" 00:00:00|";
}else if(i.matches("[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}.\\d+")) {
stringFinal += i.substring(0,19)+"|";
}else {
stringFinal += i+"|";
}
}
return(stringFinal);
}
第一个替代方案很慢,因为 104MB 被“|”分割然后,这个拆分的每个部分都会根据正则表达式逐一检查!
第二种选择是:
public static String setDataCleaner(String in) {
Pattern pattData1 = Pattern.compile("[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}.\\d+");
Pattern pattData2 = Pattern.compile("\\|[0-9]{4}-[0-9]{2}-[0-9]{2}\\|");
String newString = "";
Matcher matcher = pattData1.matcher(in);
while (matcher.find()) {
newString = in.substring(0, matcher.start()) + matcher.group().substring(0, 19)
+ in.substring(matcher.end());
}
matcher = pattData2.matcher(newString);
String temp = "";
while (matcher.find()) {
temp = newString.substring(0, matcher.start());
temp += matcher.group().substring(1, 11) + " 00:00:00|";
temp += newString.substring(matcher.end());
}
return temp;
}
第二种选择看起来更好,但是,每次出现我的正则表达式匹配时都会覆盖 temp 变量,并且作为第一次尝试,它也很慢!
所以,我找不到一个简单的替代方法,例如,我可以执行 replaAll() 并同时使用 match valeu 的部分,如下所示:
String temp = "I|123|abc|2021-01-03 12:15:33.151615645"
tmp.replaceAll("<regexDateFormatt>", initialFoundDate+" 00:00:00")
或
String temp = "I|123|abc|2021-01-03 12:15:33"
tmp.replaceAll("<regexDateFormatt>", initialFoundDate.substring(0,19))
【问题讨论】:
-
看看这个tutorial 来解析和格式化日期。
-
如果 len = 10,追加
" 00:00:00"。截断到 19 的最大 len。全部完成!