Regex for comma separated time in HH:mm or HH:mm:ss in Java e.g. 12:00,13:03:21

huangapple go评论77阅读模式
英文:

Regex for comma separated time in HH:mm or HH:mm:ss in Java e.g. 12:00,13:03:21

问题

我需要可以匹配逗号分隔的时间的正则表达式,例如 12:00、13:03:21、12:50,逗号分隔的时间可以有任意数量。在代码中,我正在使用逗号(,)来拆分,我使用 match 函数来检查这个正则表达式。

英文:

I need regex which can match Comma separated time like 12:00,13:03:21,12:50 there can be any number of comma separated times. I am splitting this with , in code I am using match function to check this regex

答案1

得分: 1

以下正则表达式可以实现这个目标:

^(?:[01]\d|2[1-3]):[0-5]\d(?::[0-5]\d)?(?:,(?:[01]\d|2[1-3]):[0-5]\d(?::[0-5]\d)?)*$

你可以在这里尝试

请注意,如果你的代码对输入执行的操作不仅仅是验证(即如果你将要使用这些时间,进行任何类型的时间计算),那么更合理的做法是将字符串按,分割,然后使用LocalTime.parse(CharSequence text)验证部分并将它们映射到更有用的数据类型中。

英文:

The following regex would do the trick :

^(?:[01]\d|2[1-3]):[0-5]\d(?::[0-5]\d)?(?:,(?:[01]\d|2[1-3]):[0-5]\d(?::[0-5]\d)?)*$

You can try it here.

Note that if your code is doing anything more with that input than validating it (i.e. if you're going to use the times as such, do any kind of time arithmetics) then it would make more sense to simply split the string over , and then use LocalTime.parse(CharSequence text) to validate the parts while mapping them into a more useful datatype.

huangapple
  • 本文由 发表于 2020年4月10日 19:24:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/61139283.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定