stringscalapattern-matching

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 :)


Solution

  • Use regular expressions, make sure you use a sequence wildcard like _*, e.g.:

    val Pattern = "(chat.*)".r
    
    serv match {
         case Pattern(_*) => "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"
    }