我在这里做错了什么:
val pattern = "([1-7]),([0-1][0-9]|[2][0-3])([0-1][0-9]|[2][0-3])".r
val pattern(count, fruit) = "7,2323"
给出:
[info] Scenario: For a set of combination of hour formats, map them to the expected 24 hours format1 *** FAILED ***
[info] scala.MatchError: 7,2323 (of class java.lang.String)
[info] at com.mf.location.os.service.util.HoursFormatUtil$.fromHours(HoursFormatUtil.scala:55)
[info] at com.mf.location.os.service.util.HoursFormatUtilSpec.$anonfun$new$9(HoursFormatUtilSpec.scala:71)
[info] at org.scalatest.OutcomeOf.outcomeOf(OutcomeOf.scala:85)
[info] at org.scalatest.OutcomeOf.outcomeOf$(OutcomeOf.scala:83)
[info] at org.scalatest.OutcomeOf$.outcomeOf(OutcomeOf.scala:104)
[info] at org.scalatest.Transformer.apply(Transformer.scala:22)
[info] at org.scalatest.Transformer.apply(Transformer.scala:20)
[info] at org.scalatest.featurespec.AnyFeatureSpecLike$$anon$1.apply(AnyFeatureSpecLike.scala:257)
[info] at org.scalatest.TestSuite.withFixture(TestSuite.scala:196)
[info] at org.scalatest.TestSuite.withFixture$(TestSuite.scala:195)
但是 println(s"matches ${pattern.matches("7,2323")}")
返回 true。
最佳答案
如果您的count
值应该是7
并且fruit
值应该是2323
,您可以使用
val pattern = "([1-7]),((?:[0-1][0-9]|2[0-3]){2})".r
val line = "7,2323"
val (count, fruit) = line match {
case pattern(count, fruit) => (count,fruit)
case _ => ("","")
}
println(s"${count} and ${fruit}")
// => 7 and 2323
参见 Scala demo .
注意 ([1-7]),((?:[0-1][0-9]|2[0-3]){2})
重构模式仅包含两个捕获组。 pattern(count, fruit)
“提取”捕获组值并将它们分配给count
和fruit
。如果没有匹配,这些变量将为空字符串。
关于regex - Scala 正则表达式模式提取器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66055991/