Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/github/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala 如何匹配前缀上的字符串并获取其余字符串?_Scala_Match - Fatal编程技术网

Scala 如何匹配前缀上的字符串并获取其余字符串?

Scala 如何匹配前缀上的字符串并获取其余字符串?,scala,match,Scala,Match,我可以这样编写代码: str match { case s if s.startsWith("!!!") => s.stripPrefix("!!!") case _ => } 但我想知道有没有更好的解决办法。例如: str match { case "!!!" + rest => rest case _ => } 因此后缀将填充字符串的其余部分,或者抛出scala.MatchError 另一种变体是: val r = """^(!!!

我可以这样编写代码:

str match {
    case s if s.startsWith("!!!") => s.stripPrefix("!!!")
    case _ =>
}
但我想知道有没有更好的解决办法。例如:

str match {
    case "!!!" + rest => rest
    case _ =>
}
因此
后缀
将填充字符串的其余部分,或者抛出
scala.MatchError

另一种变体是:

val r = """^(!!!){0,1}(.*)""".r
val r(prefix,suffix) = ...
前缀
将匹配!!!或者是空的。e、 g

(prefix, suffix) match {
   case(null, s) => "No prefix"
   case _ => "Prefix"
}

上面的内容比您可能需要的要复杂一些,但是值得一看Scala的regexp集成的强大功能。

如果这是您经常做的事情,那么创建一个提取器可能是值得的

object BangBangBangString{ 
   def unapply(str:String):Option[String]= {
       str match {
          case s if s.startsWith("!!!") => Some(s.stripPrefix("!!!"))
          case _ => None
       }
   }
}
然后您可以按如下方式使用提取器

str match{
   case BangBangBangString(rest) => println(rest)
   case _ => println("Doesn't start with !!!")
}
甚至

for(BangBangBangString(rest)<-myStringList){
   println("rest")
}
for(bangstring)(rest)问得好!
就连我都在努力寻找答案

这是一个


Scala 2.13
开始,现在可以通过以下方式对
字符串进行模式匹配:


您可以使用startsWith参数的第一个参数创建一个类似前缀提取器的类,然后像这样使用:
val-bandbangstring=new-PrefixExtractor(!!!”)
这回答了一个不同的问题。
for(BangBangBangString(rest)<-myStringList){
   println("rest")
}
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";
    }
  }
}
"!!!hello" match {
  case s"!!!$rest" => rest
  case _           => "oups"
}
// "hello"