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

Freewind picture Freewind · Jul 17, 2011 · Viewed 30.9k times · Source

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 _ =>
}

Answer

Brian Agnew picture Brian Agnew · Jul 17, 2011
val r = """^!!!(.*)""".r
val r(suffix) = "!!!rest of string"

So suffix will be populated with rest of string, or a scala.MatchError gets thrown.

A different variant would be:

val r = """^(!!!){0,1}(.*)""".r
val r(prefix,suffix) = ...

And prefix will either match the !!! or be null. e.g.

(prefix, suffix) match {
   case(null, s) => "No prefix"
   case _ => "Prefix"
}

The above is a little more complex than you might need, but it's worth looking at the power of Scala's regexp integration.