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

时间:2012-03-19 12:42:57

标签: string scala pattern-matching

我有以下内容:

serv match {

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

}

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

var serv = "chat.message"

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

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

3 个答案:

答案 0 :(得分:49)

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

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

答案 1 :(得分:48)

使用正则表达式;)

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

serv match {
     case Pattern(chat) => "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"
}

答案 2 :(得分:0)

如果要在使用正则表达式时消除任何分组,请确保使用_*之类的序列通配符(按照Scala's documentation)。

在上面的示例中:

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

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