How to match a string on a prefix and get the rest?

Viewed 34113

I can write the code like this:

str match {
    case s if s.startsWith("!!!") => s.stripPrefix("!!!")
    case _ =>
}

But I want to know is there any better solutions. For example:

str match {
    case "!!!" + rest => rest
    case _ =>
}
4 Answers

Starting Scala 2.13, it's now possible to pattern match a String by unapplying a string interpolator:

"!!!hello" match {
  case s"!!!$rest" => rest
  case _           => "oups"
}
// "hello"
Related