替换字符串中可能出现可变次数的模式的习语是,取自the documentation of Matcher.appendReplacement,是:
// '2017-03-08 10:59:31'
Pattern dateTimePattern = Pattern.compile("'\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}'");
Matcher dateTimeMatcher = dateTimePattern.matcher("(1,'Ctx_Log-Log','',"
+ "'08.03.2017','2017-03-08 10:59:31','10:59:32','2017-03-08 10:59:41')");
StringBuffer result = new StringBuffer();
while (dateTimeMatcher.find()) {
dateTimeMatcher.appendReplacement(result, "To_TIMESTAMP(" + dateTimeMatcher.group() + ')');
}
dateTimeMatcher.appendTail(result);
System.out.println(result.toString());
这个sn-p的输出是:
(1,'Ctx_Log-Log','','08.03.2017',To_TIMESTAMP('2017-03-08 10:59:31'),'10:59:32',To_TIMESTAMP('2017- 03-08 10:59:41'))
如果是我,我想添加对日期时间字符串的进一步验证,以确保我不会替换看起来像日期时间的东西:
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("''uuuu-MM-dd HH:mm:ss''");
Pattern dateTimePattern = Pattern.compile("'\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}'");
// 2017-77-77 77:77:77 is not a valid date-time and should not be replaced.
Matcher dateTimeMatcher = dateTimePattern.matcher("(1,'Ctx_Log-Log','',"
+ "'08.03.2017','2017-03-08 10:59:31','10:59:32','2017-77-77 77:77:77')");
StringBuffer result = new StringBuffer();
while (dateTimeMatcher.find()) {
String old = dateTimeMatcher.group();
try {
// For validation try to parse the string.
LocalDateTime.parse(old, dtf);
dateTimeMatcher.appendReplacement(result, "To_TIMESTAMP(" + old + ')');
} catch (DateTimeParseException dtpe) {
// Validation failed, this was not a date-time.
System.err.println("Not replacing invalid date-time " + old);
// To avoid changing anything replace the string with itself.
dateTimeMatcher.appendReplacement(result, old);
}
}
dateTimeMatcher.appendTail(result);
System.out.println(result.toString());
不替换无效的日期时间'2017-77-77 77:77:77'
(1,'Ctx_Log-Log','','08.03.2017',To_TIMESTAMP('2017-03-08
10:59:31'),'10:59:32','2017-77-77 77:77:77')