DateTimeFormatter 中的通配符

Wildcard in DateTimeFormatter

我需要将字符串解析为 LocalDate。该字符串在正则表达式中看起来像 31.* 03 2016(即 .* 表示天数后可能有 0 个或更多未知字符)。

示例input/output:31xy 03 2016 ==> 2016-03-31

我希望在 DateTimeFormatter 文档中找到通配符语法以允许使用如下模式:

LocalDate.parse("31xy 03 2016", DateTimeFormatter.ofPattern("dd[.*] MM yyyy"));

但我找不到任何东西。

有没有一种简单的方法可以用 DateTimeFormatter 来表示可选的未知字符?

ps:我显然可以在解析之前修改字符串,但这不是我想要的。

java.time 中没有对此的直接支持。

最接近的是 parse(CharSequence,ParsePosition) 使用两种不同的格式化程序。

// create the formatter for the first half
DateTimeFormatter a = DateTimeFormatter.ofPattern("dd")

// setup a ParsePosition to keep track of where we are in the parse
ParsePosition pp = new ParsePosition();

// parse the date, which will update the index in the ParsePosition
String str = "31xy 03 2016";
int dom = a.parse(str, pp).get(DAY_OF_MONTH);

// some logic to skip the messy 'xy' part
// logic must update the ParsePosition to the start of the month section
pp.setIndex(???)

// use the parsed day-of-month in the formatter for the month and year
DateTimeFormatter b = DateTimeFormatter.ofPattern("MM yyyy")
    .parseDefaulting(DAY_OF_MONTH, dom);

// parse the date, using the *same* ParsePosition
LocalDate date = b.parse(str, pp).query(LocalDate::from);

虽然以上内容未经测试,但基本上应该可以使用。但是,手动解析它会容易得多。

我会分两步完成,使用正则表达式将原始字符串转换为 LocalDate 可以解析的内容,例如:

String dateSource = "31xy 03 2016";
String normalizedDate = dateSource.replaceFirst("^(\d+).*? (\d+ \d+)", " ");
LocalDate date = LocalDate.parse(normalizedDate, DateTimeFormatter.ofPattern("dd MM yyyy"));
System.out.println(date);

我知道这不是你要的。