ass*_*ias 11 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"));
Run Code Online (Sandbox Code Playgroud)
但我找不到任何东西.
是否有一种简单的方法来表达可选的未知字符DateTimeFormatter
?
ps:我可以在解析之前修改字符串,但这不是我要求的.
对此没有直接的支持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);
Run Code Online (Sandbox Code Playgroud)
虽然以上是未经测试的,但基本上应该可行.但是,手动解析它会容易得多.
归档时间: |
|
查看次数: |
2282 次 |
最近记录: |