我有以下内容:
serv match {
case "chat" => Chat_Server ! Relay_Message(serv)
case _ => null
}
问题是有时我还会在 serv 字符串的末尾传递一个附加参数,所以:
var serv = "chat.message"
有没有办法可以匹配字符串的一部分,以便它仍然被发送到 Chat_Server?
感谢您的帮助,非常感谢:)
使用正则表达式,确保使用像
_*
这样的序列通配符(根据 [Scala 的文档][1]),例如:
val Pattern = "(chat.*)".r
serv match {
case Pattern(_*) => "It's a chat"
case _ => "Something else"
}
使用正则表达式,您甚至可以轻松拆分参数和基本字符串:
val Pattern = "(chat)(.*)".r
serv match {
case Pattern(chat, param) => "It's a %s with a %s".format(chat, param)
case _ => "Something else"
}
将模式匹配绑定到变量并使用 guard 确保变量以“chat”开头
// msg is bound with the variable serv
serv match {
case msg if msg.startsWith("chat") => Chat_Server ! Relay_Message(msg)
case _ => null
}
如果您想在使用正则表达式时消除任何分组,请确保使用像
_*
这样的序列通配符(根据 Scala 的文档)。
从上面的例子来看:
val Pattern = "(chat.*)".r
serv match {
case Pattern(_*) => "It's a chat"
case _ => "Something else"
}