简体   繁体   English

不推荐使用-Scala Regex模式匹配

[英]Deprecated - Scala Regex Pattern Matching

Currently as of Scala 2.11 using a regex expression in a pattern matching is not encouraged, unless you're matching against a Seq[Char] or Match, is there an alternative approach. 目前,从Scala 2.11开始,不建议在模式匹配中使用正则表达式,除非您要针对Seq [Char]或Match进行匹配,否则还有另一种方法。 Currently I've implemented a getValueV2 with the Seq[Char] strategy in the following example, though it's verbose and it doesn't look good enough. 目前,在以下示例中,我已经用Seq [Char]策略实现了getValueV2,尽管它很冗长且看起来还不够好。

What other suggestions do you have for replacing a regex, 您对于替换正则表达式还有什么其他建议,

trait MyHelper {
  //param Regex is deprecated
 def getValue(option: Option[scala.Any]): String = {
  val param = """(?:String|Boolean)Option\((.*)\)""".r
  option.getOrElse("") match {
    case param(s) => s
    case arr: Array[_] => arr.mkString("")
    case _ => ""
  }
}

def getValueV2(option: Option[scala.Any]): String = {
  option.getOrElse("") match {
      case s : String => s.toSeq match {
        case p if p.endsWith(")") => p match {
        case Seq('S', 't', 'r', 'i', 'n', 'g', 'O', 'p', 't', 'i', 'o', 'n', '(', suffix@_*) => suffix.toString.substring(0, suffix.length -1)
          case Seq('B', 'o', 'o', 'l', 'e', 'a', 'n', 'O', 'p', 't', 'i', 'o', 'n', '(',  suffix@_*) => suffix.toString.substring(0, suffix.length -1)
          case _ => s                   
        }
        case _ => s 
      }
      case arr: Array[_] => arr.mkString("")
      case _ => ""
    }
  }
}

I've been looking for another library called kantan.regex but It doesn't seem to have a big community. 我一直在寻找另一个名为kantan.regex的库,但它似乎没有一个很大的社区。 What would be the best approach here, just keep with the regex and ignore the deprecated warnings? 在这里最好的方法是什么,只使用正则表达式,而忽略不推荐使用的警告?

Since you're only interested in matching against String inputs, test for type before applying the Regex. 由于您仅对匹配String输入感兴趣,因此在应用Regex之前先测试类型。

def getValue(option: Option[scala.Any]): String = {
  val param = """(?:String|Boolean)Option\((.*)\)""".r
  option.getOrElse("") match {
    case str: String => str match {
      case param(s) => s
      case _ => ""
    }
    case arr: Array[_] => arr.mkString("")
    case _ => ""
  }
}

This compiles without warning. 编译时没有警告。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM