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 _ => }
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.
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.
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.
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") }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With