Java DateTimeFormatter中的通配符

Java DateTimeFormatter中的通配符,java,parsing,java-time,Java,Parsing,Java Time,我需要将字符串解析为LocalDate。该字符串在正则表达式中类似于31.*03 2016(即*表示在天数之后可能有0个或更多未知字符) 输入/输出示例:31xy 03 2016==>2016-03-31 我希望在DateTimeFormatter文档中找到一种通配符语法,以允许以下模式: LocalDate.parse("31xy 03 2016", DateTimeFormatter.ofPattern("dd[.*] MM yyyy")); 但我什么也找不到 有没有一种简单的方法可以用D

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

输入/输出示例:
31xy 03 2016
==>
2016-03-31

我希望在DateTimeFormatter文档中找到一种通配符语法,以允许以下模式:

LocalDate.parse("31xy 03 2016", DateTimeFormatter.ofPattern("dd[.*] MM yyyy"));
但我什么也找不到

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


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

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

最接近的方法是使用两个不同的格式化程序

// 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);

虽然上述方法未经测试,但基本上是可行的。但是,手动解析要容易得多。

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

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

我知道这不是您所要求的。

在将字符串传递给
日期时间格式设置程序之前,您是否有理由不想对其进行预处理?您还可以创建自己的类,该类扩展了
DateTimeFormatter
,并重写了
of pattern()
方法,但这似乎不可取。我更喜欢DateTimeFormatter的优雅解决方案-如果它不存在,我会选择方案B。DateTimeFormatter是最终的,因此不可扩展。啊,我不知道,很高兴知道!请定义什么对你来说是“简单的”。这是一个基于模式的解决方案,其中char*表示剩余的最小模式宽度的任何字符数,还是一个生成器支持的方法适合您?我已经考虑了您的要求,可以提供一个基于我的lib Time4J的解决方案(下一个版本v4.14将于本月发布),另见此。如果您有任何问题或需要澄清,请让我知道。也许是一个“宽松”的解析器,只会跳过不可解析的字符?(使用宽松的解析器样式是行不通的)你不能总是得到你想要的。但如果你有时尝试,你可能会发现你得到了你需要的。