Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 正则表达式的Matcher为false,而表达式、模式和字符串均有效_Regex_Kotlin - Fatal编程技术网

Regex 正则表达式的Matcher为false,而表达式、模式和字符串均有效

Regex 正则表达式的Matcher为false,而表达式、模式和字符串均有效,regex,kotlin,Regex,Kotlin,我使用的正则表达式如下所示: @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").withZ

我使用的正则表达式如下所示:

@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)
}
出于某种原因,IsMatchToAcceptedDataPattern返回false,这可能表明我的正则表达式有问题,但在多个正则表达式网站上检查时,我得到的是有效匹配。你知道为什么吗

你自己试试吧: 或在此:

my regex-raw(如网站中所示):

(\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):([0-5]?\d)

像这样返回的模式示例(返回时在“T”附近没有“'”):

2021-04-01T11:12:51(当我调试时,这就是我得到的)

日期模式:

yyyy-MM ddTHH:MM:ss


有人能告诉我吗?

您使用的是
matcher.matches()
,它类似于pre-and-appending
^
resp<代码>$到您的正则表达式

相反,您应该:

  • 使用
    matcher.find()
    ,如果可以找到匹配项,则返回
    true
  • \d{2}
    前置到您的正则表达式中,并且仍然使用
    matcher.matches()