raul782 raul782 - 1 month ago 7
Scala Question

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. 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.

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. What would be the best approach here, just keep with the regex and ignore the deprecated warnings?

Answer

Since you're only interested in matching against String inputs, test for type before applying the 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.