Java中的ISO Duration格式验证

3
我谷歌搜索了一下,但是没有找到任何好的解决方案来验证输入字符串是否符合ISO持续时间格式。如果有人有任何想法或解决方案,可能使用正则表达式或函数,将会帮助很多人。
注意:持续时间的格式为[-]P[n]DT[n]H[n]M[n][.frac_secs]S,其中n指定元素的值(例如,4H表示4小时)。这表示ISO持续时间格式的一个子集,任何其他持续时间字母(包括有效的ISO字母,如Y和M)都会导致错误。
Example 1,
input string = "P100DT4H23M59S";
expected output = 100 04:23:59.000000

Example 2,
input string = "P2MT12H";
expected output = error, because the month designator, '2M', isn't allowed.

Example 3,
input string = "100 04:23:59";
expected output = 100 04:23:59.000000

.


1
http://stackoverflow.com/a/36319272/3832970? - Wiktor Stribiżew
@WiktorStribiżew,我只想验证输入字符串而不是转换它。 - subodh
1
你写了 input string = "P100DT4H23M59S"; expected output = 100 04:23:59.000000 - 这是转换,对吧? - Wiktor Stribiżew
类似这样的东西:https://regex101.com/r/mB4iY9/1? - Thomas Ayoub
@RC. 你有没有想过如何在Java 7中实现相同的功能? - subodh
显示剩余3条评论
1个回答

2

java.time.Duration

java.time类在解析/生成文本时默认使用ISO 8601格式。

使用Duration类。

调用Duration#parse方法。当遇到错误输入时,捕获DateTimeParseException异常。

String input = "P100DT4H23M59S";
try
{
    Duration duration = Duration.parse( input );
}
catch ( DateTimeParseException e )
{
    System.out.println( "ERROR - Faulty input." );
}

Java中的Duration类表示一个与时间轴无关的时间跨度,以通用24小时天(而非日历天)、小时、分钟和秒为单位。(有关日历天,请参见Period类。)
因此,Duration#parse会自动拒绝您不需要的年、月和周输入。
String input = "P2MT12H";
try
{
    Duration duration = Duration.parse( input );
}
catch ( DateTimeParseException e )
{
    System.out.println( "ERROR - Faulty input." );
}

当运行时:

错误 - 输入有误。


这是在生产代码中推荐的做法。针对OP和其他未来的访问者:不要在生产环境中使用正则表达式(如评论中所建议)作为解决此问题的方法。但是,您可以尝试使用正则表达式作为学习和娱乐的解决方案。 - Arvind Kumar Avinash
“PT25H” 不是无效值吗?在代码中,这个值被解析而没有任何错误信息。 - firstpostcommenter
1
@firstpostcommenter 不,输入25小时没有问题。在“Duration”中,这意味着一天24小时和一个小时。 “Duration”表示以小时-分钟-秒-纳秒为单位的时间跨度。我不知道最大值,但是您可以拥有至少20亿小时 - Basil Bourque

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接