regex - Scala 正则表达式模式提取器

标签 regex scala

我在这里做错了什么:

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)“提取”捕获组值并将它们分配给countfruit。如果没有匹配,这些变量将为空字符串。

关于regex - Scala 正则表达式模式提取器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66055991/

相关文章:

scala - Spark 应用程序抛出 javax.servlet.FilterRegistration

java - 为 scala.js 指定 mainClass?

scala - 如何在java函数中返回Scala `Unit`类型

scala - Spark中ALS的实现

c# - 如何在 C# 中替换字符串的一部分?

c# - 正则表达式 - 用于匹配括号之间的字母字符的模式

python - 根据句子上下文检测单词 you 是主语还是宾语代词。

scala - 如何得到两个RDD的乘积?

regex - 在Elasticsearch中不含正则表达式

java - 如何替换所有星号?