string Scala - 大小写匹配部分字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9770416/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scala - case match partial string
提问by jhdevuk
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:
问题是有时我还会在 serv 字符串的末尾传递一个额外的参数,所以:
var serv = "chat.message"
Is there a way I can match a part of the string so it still gets sent to Chat_Server?
有没有办法可以匹配字符串的一部分,以便它仍然被发送到 Chat_Server?
Thanks for any help, much appreciated :)
感谢您的帮助,非常感谢:)
回答by Kyle
Have the pattern matching bind to a variable and use a guardto ensure the variable begins with "chat"
将模式匹配绑定到一个变量并使用保护来确保变量以“chat”开头
// msg is bound with the variable serv
serv match {
case msg if msg.startsWith("chat") => Chat_Server ! Relay_Message(msg)
case _ => null
}
回答by om-nom-nom
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"
}
回答by jverce
In case you want to dismiss any groupings when using regexes, make sure you use a sequence wildcard like _*
(as per Scala's documentation).
如果您想在使用正则表达式时取消任何分组,请确保使用序列通配符_*
(根据Scala 的文档)。
From the example above:
从上面的例子:
val Pattern = "(chat.*)".r
serv match {
case Pattern(_*) => "It's a chat"
case _ => "Something else"
}