问题描述
我需要将字符串解析为LocalDate
.该字符串看起来像用正则表达式表示的31.* 03 2016
(即.*
表示在日期号之后可能有0个或更多的未知字符).
I need to parse a string into a LocalDate
. The string looks like 31.* 03 2016
in regex terms (i.e. .*
means that there may be 0 or more unknown characters after the day number).
示例输入/输出:31xy 03 2016
==> 2016-03-31
Example input/output: 31xy 03 2016
==> 2016-03-31
我希望在DateTimeFormatter文档中找到通配符语法,以允许使用以下模式:
I was hoping to find a wildcard syntax in the DateTimeFormatter documentation to allow a pattern such as:
LocalDate.parse("31xy 03 2016", DateTimeFormatter.ofPattern("dd[.*] MM yyyy"));
但是我什么也找不到.
是否有一种简单的方法来用DateTimeFormatter
表示可选的未知字符?
Is there a simple way to express optional unknown characters with a DateTimeFormatter
?
ps:我显然可以在解析字符串之前对其进行修改,但这不是我要的.
ps: I can obviously modify the string before parsing it but that's not what I'm asking for.
推荐答案
java.time
中没有对此的直接支持.
There is no direct support for this in java.time
.
最接近的方法是使用使用两个不同的格式化程序解析(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);
虽然以上内容未经测试,但基本上可以正常工作.但是,手动解析会容易得多.
While the above is untested it should basically work. However, it would be far easier parse it manually.
这篇关于DateTimeFormatter中的通配符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!