Scala - case match partial string

瘦欲@ 提交于 2019-12-04 08:00:59

问题


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


回答1:


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"
}



回答2:


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
}



回答3:


In case you want to dismiss any groupings when using regexes, make sure you use a sequence wildcard like _* (as per Scala's documentation).

From the example above:

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

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


来源:https://stackoverflow.com/questions/9770416/scala-case-match-partial-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!