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

Man*_*dha 4 scala

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

到目前为止,我已经使用过的split方法,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 {..}
Run Code Online (Sandbox Code Playgroud)

我该怎么做match呢?

pra*_*upd 6

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

val tag = "course-subject-topic"

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

模式匹配也可以有if如下防护,

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

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


Xav*_*hot 5

从开始Scala 2.13,可以String通过不应用字符串插值器来对a进行模式匹配:

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