在我的代码中,字符串应具有以下结构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 {..}
做同样的事情?
答案 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")
}
答案 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