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 :)
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 .
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.
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.
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
}
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"
}
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