scala 如何匹配前缀上的字符串并获得其余部分?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6724679/
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
How to match a string on a prefix and get the rest?
提问by Freewind
I can write the code like this:
我可以这样写代码:
str match {
case s if s.startsWith("!!!") => s.stripPrefix("!!!")
case _ =>
}
But I want to know is there any better solutions. For example:
但我想知道有没有更好的解决方案。例如:
str match {
case "!!!" + rest => rest
case _ =>
}
采纳答案by Brian Agnew
val r = """^!!!(.*)""".r
val r(suffix) = "!!!rest of string"
So suffixwill be populated with rest of string, or a scala.MatchErrorgets thrown.
所以suffix将填充string 的其余部分,或者 ascala.MatchError被抛出。
A different variant would be:
一个不同的变体是:
val r = """^(!!!){0,1}(.*)""".r
val r(prefix,suffix) = ...
And prefixwill either match the !!! or be null. e.g.
并且prefix将匹配 !!! 或为空。例如
(prefix, suffix) match {
case(null, s) => "No prefix"
case _ => "Prefix"
}
The above is a little more complex than you might need, but it's worth looking at the power of Scala's regexp integration.
上面的内容可能比您需要的要复杂一些,但值得一看 Scala 正则表达式集成的强大功能。
回答by Dave Griffith
If it's the sort of thing you do often, it's probably worth creating an extractor
如果这是您经常做的事情,那么可能值得创建一个提取器
object BangBangBangString{
def unapply(str:String):Option[String]= {
str match {
case s if s.startsWith("!!!") => Some(s.stripPrefix("!!!"))
case _ => None
}
}
}
Then you can use the extractor as follows
然后你可以使用提取器如下
str match{
case BangBangBangString(rest) => println(rest)
case _ => println("Doesn't start with !!!")
}
or even
甚至
for(BangBangBangString(rest)<-myStringList){
println("rest")
}
回答by Xavier Guihot
Starting Scala 2.13, it's now possible to pattern match a Stringby unapplying a string interpolator:
开始Scala 2.13,现在可以String通过不应用字符串插值器来模式匹配 a :
"!!!hello" match {
case s"!!!$rest" => rest
case _ => "oups"
}
// "hello"
回答by Krishna Kumar
Good question ! Even i was trying a lot to find out the answer.
好问题 !甚至我也很努力地想找出答案。
Here is a good link where I found the answer
object _04MatchExpression_PatternGuards {
def main(args: Array[String]): Unit = {
val url: String = "Jan";
val monthType = url match {
case url if url.endsWith(".org") => "Educational Websites";
case url if url.endsWith(".com") => "Commercial Websites";
case url if url.endsWith(".co.in") => "Indian Websites"
case _ => "Unknow Input";
}
}
}

