Scala - 大小写匹配部分字符串

jhd*_*vuk 35 string scala pattern-matching

我有以下内容:

serv match {

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

}
Run Code Online (Sandbox Code Playgroud)

问题是有时我还会在serv字符串的末尾传递一个额外的参数,所以:

var serv = "chat.message"
Run Code Online (Sandbox Code Playgroud)

有没有办法可以匹配字符串的一部分,所以它仍然被发送到Chat_Server?

谢谢你的帮助,非常感谢:)

Kyl*_*yle 50

让模式匹配绑定到变量并使用guard来确保变量以"chat"开头

// msg is bound with the variable serv
serv match {
  case msg if msg.startsWith("chat") => Chat_Server ! Relay_Message(msg)
  case _ => null
}
Run Code Online (Sandbox Code Playgroud)

  • 在第一种情况表达中它被称为*guard* (2认同)

om-*_*nom 49

使用正则表达式;)

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

serv match {
     case Pattern(chat) => "It's a chat"
     case _ => "Something else"
}
Run Code Online (Sandbox Code Playgroud)

使用正则表达式,您甚至可以轻松地拆分参数和基本字符串:

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

serv match {
     case Pattern(chat,param) => "It's a %s with a %s".format(chat,param)
     case _ => "Something else"
}
Run Code Online (Sandbox Code Playgroud)

  • 在你的情况下,pattenr匹配中的"chat"变量显然是无用的,你可以用`Pattern(_)替换它 (2认同)