使用Scala的案例类模式中的正则表达式模式

时间:2015-08-31 14:49:20

标签: regex scala pattern-matching case-class

这一定是愚蠢的,但我想知道是否有人可以帮助我。案例类匹配中的以下正则表达式模式匹配无法正常工作。有人能提供一些见解吗?感谢。

object Confused {

  case class MyCaseClass(s: String)

  val WS = """\s*""".r

  def matcher(myCaseClass: MyCaseClass) = myCaseClass match {
    case MyCaseClass(WS(_)) => println("Found WS")
    case MyCaseClass(s) => println(s"Found >>$s<<")
  }

  def main(args: Array[String]): Unit = {
    val ws = " "

    matcher(MyCaseClass(ws))
  }
}

我希望模式匹配中的第一个案例是匹配的案例,但事实并非如此。

打印

  

找到&gt;&gt; &LT;&LT;

1 个答案:

答案 0 :(得分:7)

应该是:

val WS = """(\s*)""".r

对于您的问题,您希望匹配空格模式,在 Scala

  

正则表达式用于确定字符串是否与a匹配   模式,如果是,则提取或转换匹配的部分。

用于提取匹配部分,我们需要使用group来模式化字符串。这意味着我们需要在模式字符串周围使用parentheses

示例:

val date = """(\d\d\d\d)-(\d\d)-(\d\d)""".r
"2004-01-20" match {
  case date(year, month, day) => s"$year was a good year for PLs."
}