2 回答

TA貢獻(xiàn)1155條經(jīng)驗(yàn) 獲得超0個(gè)贊
這是一個(gè)基本算法,它將在管道分隔文件中查找,將“看起來像”日期的值替換為當(dāng)前日期,然后將所有內(nèi)容寫回新文件。它使用YYYYDDMM您在問題中描述的格式,但它可能應(yīng)該是YYYYMMDD,我已經(jīng)注意到您需要在哪里進(jìn)行更改。這通過日期驗(yàn)證和錯(cuò)誤處理減少了一些角落,以盡量保持相對較短,但我過度評論以嘗試解釋所有內(nèi)容:
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
語句來確保正確關(guān)閉輸入和輸出文件。

TA貢獻(xiàn)2012條經(jīng)驗(yàn) 獲得超12個(gè)贊
您可以使用如下正則表達(dá)式。
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)";
它并不完美,但可以匹配大多數(shù)日期。例如,它將消除月份超過 12 的日期。此外,它適用于 2099 年之前的日期。它不處理像 6 月有 30 天這樣的日期規(guī)則。它將匹配天數(shù)在 1-31 之間的任何日期。
您不能用于equals
日期。你將不得不使用Pattern.matches(regex, string)
添加回答
舉報(bào)