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

Bil*_*ton 3 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))
  }
}
Run Code Online (Sandbox Code Playgroud)

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

这打印

发现>> <<

che*_*ohi 10

它应该是:

val WS = """(\s*)""".r
Run Code Online (Sandbox Code Playgroud)

对于你的问题,你想匹配一个空间模式,在Scala中,

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

用于提取匹配部分,我们需要使用它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."
}
Run Code Online (Sandbox Code Playgroud)