如何根据字符对字符串进行模式匹配?

时间:2019-04-27 20:21:51

标签: scala

在我的代码中,字符串应具有以下结构part1-part2-part3。不同的部分用-隔开,只能有3个部分。

到目前为止,我已经使用了split的{​​{1}}方法,并且可以检查返回的String的长度以验证结构:

Array

如何使用val tagDetails: Array[String] = tag.split('-') //syntax of received tag is part1-part2-part3 if (tagDetails.length == 3) { val course: String = tagDetails(0) val subject: String = tagDetails(1) val topic: String = tagDetails(2) println("splitted tag " + course + ", " + subject + ", " + topic) } else {..} 做同样的事情?

2 个答案:

答案 0 :(得分:6)

您可以使用match分解拆分值数组。

val tag = "course-subject-topic"

tag.split('-') match {
  case Array(course, subject, topic) =>
    println("splitted tag " + course + ", " + subject + ", " + topic)
  case _ => println("Oops")
}

模式匹配还可以具有if防护,如下所示

tag.split('-') match {
  case Array(course, subject, topic) if course != subject =>
    println("splitted tag " + course + ", " + subject + ", " + topic)
  case _ => println("Oops")
}

参考-https://docs.scala-lang.org/tour/pattern-matching.html

答案 1 :(得分:5)

Scala 2.13开始,可以通过unapplying a string interpolator通过chisel模式匹配String

"part1-part2-part3" match {
  case s"$course-$subject-$topic" =>
    println(s"Split tag $course, $subject, $topic")
  case _ =>
    println("Oops")
}
// Splitted tag part1, part2, part3