2 回答
TA贡献1155条经验 获得超0个赞
这是一个基本算法,它将在管道分隔文件中查找,将“看起来像”日期的值替换为当前日期,然后将所有内容写回新文件。它使用YYYYDDMM您在问题中描述的格式,但它可能应该是YYYYMMDD,我已经注意到您需要在哪里进行更改。这通过日期验证和错误处理减少了一些角落,以尽量保持相对较短,但我过度评论以尝试解释所有内容:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DateReplacer
{
private static final Pattern DATE_MATCHER =
Pattern.compile("(?:(?:19|20)[0-9]{2})([0-9]{2})([0-9]{2})");
public static void main(String... args)
throws Exception
{
// These are the paths to our input and output files
Path input = Paths.get("input.dat");
Path output = Paths.get("output.dat");
// We need to get today's date in YYYYDDMM format, so we create a
// DateFormatter for that. If it turns out that your date format is
// actually YYYYMMDD, you can just use DateFormatter.BASIC_ISO_DATE
// instead.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyddMM");
String todaysDate = LocalDate.now().format(formatter);
// Use try-with-resources to create a reader & writer
try (BufferedReader reader = Files.newBufferedReader(input);
BufferedWriter writer = Files.newBufferedWriter(output)) {
String line;
// Read lines until there are no more lines
while ((line = reader.readLine()) != null) {
// Split them on the | character, notice that it needs to be
// escaped because it is a regex metacharacter
String[] columns = line.split("\\|");
// Iterate over every column...
for (int i = 0; i < columns.length; i++) {
// ... and if the value looks like a date ...
if (isDateLike(columns[i])) {
// ... overwrite with today's date.
columns[i] = todaysDate;
}
}
// Re-join the columns with the | character and write it out
writer.write(String.join("|", columns));
writer.newLine();
}
}
}
private static boolean isDateLike(String str)
{
// Avoid the regular expression if we can
if (str.length() != 8) {
return false;
}
Matcher matcher = DATE_MATCHER.matcher(str);
if (matcher.matches()) {
// If it turns out that your date format is actually YYYYMMDD
// you will need to swap these two lines.
int day = Integer.parseInt(matcher.group(1), 10);
int month = Integer.parseInt(matcher.group(2), 10);
// We don't need to validate year because we already know
// it is between 1900 and 2099 inclusive
return day >= 1 && day <= 31 && month >= 1 && month <= 12;
}
return false;
}
}
此示例使用一条try-with-resources语句来确保正确关闭输入和输出文件。
TA贡献2012条经验 获得超12个赞
您可以使用如下正则表达式。
String regex = "(19|20)[0-9][0-9](0[1-9]|1[0-2])(0[1-9]|1[0-9]|2[0-9]|30|31)";
它并不完美,但可以匹配大多数日期。例如,它将消除月份超过 12 的日期。此外,它适用于 2099 年之前的日期。它不处理像 6 月有 30 天这样的日期规则。它将匹配天数在 1-31 之间的任何日期。
您不能用于equals日期。你将不得不使用Pattern.matches(regex, string)
添加回答
举报
