Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pattern match a string based on a character?

Tags:

scala

In my code, a string is expected to have the following structure part1-part2-part3. The different parts are separated by - and there can only be 3 parts.

So far I have used split method of String and can check the length of the returned Array to validate the structure:

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 {..}

How can I do the same using match?

like image 803
Manu Chadha Avatar asked Dec 18 '22 17:12

Manu Chadha


1 Answers

You can destructure the Array of splitted values with match.

val tag = "course-subject-topic"

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

pattern match can also have if guard as below,

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

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

like image 59
prayagupa Avatar answered Jan 08 '23 22:01

prayagupa