Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

match

scala

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 _ => } 
like image 251
Freewind Avatar asked Jul 17 '11 15:07

Freewind


People also ask

What is pattern matching in Scala?

Pattern matching is a mechanism for checking a value against a pattern. A successful match can also deconstruct a value into its constituent parts. It is a more powerful version of the switch statement in Java and it can likewise be used in place of a series of if/else statements.

What will the regular expression match?

By default, regular expressions will match any part of a string. It's often useful to anchor the regular expression so that it matches from the start or end of the string: ^ matches the start of string. $ matches the end of the string.


2 Answers

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.

like image 171
Brian Agnew Avatar answered Oct 02 '22 16:10

Brian Agnew


If it's the sort of thing you do often, it's probably worth creating an extractor

object BangBangBangString{     def unapply(str:String):Option[String]= {        str match {           case s if s.startsWith("!!!") => Some(s.stripPrefix("!!!"))           case _ => None        }    } } 

Then you can use the extractor as follows

str match{    case BangBangBangString(rest) => println(rest)    case _ => println("Doesn't start with !!!") } 

or even

for(BangBangBangString(rest)<-myStringList){    println("rest") } 
like image 26
Dave Griffith Avatar answered Oct 02 '22 15:10

Dave Griffith