我使用正则表达式,如下所示:
@Test
fun timePatternFromInstantIsValid() {
val instantOfSometimeEarlier = Instant.now().minus(Duration.ofMinutes((1..3).random().toLong()))
val timeOfEvent = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss").withZone(ZoneId.of("UTC")).format(instantOfSometimeEarlier)
val regex = "(\\d{2}-(0[1-9]|1[0-2])-(0[1-9]|[12]\\d|3[01]))T(?:(?:([01]?\\d|2[0-3]):)?([0-5]?\\d):)?([0-5]?\\d)"
val acceptedDatePattern: Pattern = Pattern.compile(regex)
val matcher: Matcher = microsoftAcceptedDatePattern.matcher(timeOfEvent)
val isMatchToAcceptedDatePattern: Boolean = matcher.matches()
print(isMatchToAcceptedDatePattern)
}由于某种原因,isMatchToAcceptedDatePattern返回false,这可能表明我的regex中有问题,但是,当在多个regex网站上检查它时,我得到了一个有效的匹配。知道为什么吗?
自己试试:https://www.regextester.com/或这里:https://regex101.com/
我的regex - raw (如在网站上):
(\d{2}-(01-9|10-2)-(01-9|12\d|301))T(?:(?:(01?\d|20-3):)?(0-5?\d):)?(0-5?\d)
像这样返回的模式示例(在“T”附近没有“‘”返回):
2021-04-01T11:12:51 (当我调试时,这就是我得到的)
日期模式:
yyyy mm-ddTHH:mm:ss
有人能给我点火吗?
发布于 2021-04-01 12:14:12
您使用的是matcher.matches(),它类似于^ resp的预和附加。$给你的裁判官。这样的审判是行不通的。
相反,您应该要么:
matcher.find(),如果可以找到匹配项,则返回true。\d{2}添加到regex中,并仍然使用matcher.matches():演示https://stackoverflow.com/questions/66904125
复制相似问题