Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala - case match partial string

I have the following:

serv match {

    case "chat" => Chat_Server ! Relay_Message(serv)
    case _ => null

}

The problem is that sometimes I also pass an additional param on the end of the serv string, so:

var serv = "chat.message"

Is there a way I can match a part of the string so it still gets sent to Chat_Server?

Thanks for any help, much appreciated :)

like image 784
jahilldev Avatar asked Mar 19 '12 12:03

jahilldev


People also ask

What is case _ in Scala?

case _ => does not check for the type, so it would match anything (similar to default in Java). case _ : ByteType matches only an instance of ByteType . It is the same like case x : ByteType , just without binding the casted matched object to a name x .

Which method of case class allows using objects in pattern matching?

The match method takes a number of cases as an argument. Each alternative takes a pattern and one or more expressions that will be performed if the pattern matches.

How does pattern matching work?

Pattern Matching works by "reading" through text strings to match patterns that are defined using Pattern Matching Expressions, also known as Regular Expressions. Pattern Matching can be used in Identification as well as in Pre-Classification Processing, Page Processing, or Storage Processing.


2 Answers

Have the pattern matching bind to a variable and use a guard to ensure the variable begins with "chat"

// msg is bound with the variable serv
serv match {
  case msg if msg.startsWith("chat") => Chat_Server ! Relay_Message(msg)
  case _ => null
}
like image 86
Kyle Avatar answered Oct 07 '22 12:10

Kyle


Use regexes ;)

val Pattern = "(chat.*)".r

serv match {
     case Pattern(chat) => "It's a chat"
     case _ => "Something else"
}

And with regexes you can even easily split parameter and base string:

val Pattern = "(chat)(.*)".r

serv match {
     case Pattern(chat,param) => "It's a %s with a %s".format(chat,param)
     case _ => "Something else"
}
like image 36
om-nom-nom Avatar answered Oct 07 '22 11:10

om-nom-nom