Bill Barrington
Bill Barrington

Reputation: 188

Regex Pattern Within Case Class Pattern Using Scala

This has gotta be something stupid, but I'm wondering if someone can help me out here. The following regex pattern match within a case class match is not working as I would expect. Can someone provide some insight? Thanks.

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))
  }
}

I would expect the the first case in the pattern match to be the one that matches, but it is not.

This prints

Found >> <<

Upvotes: 3

Views: 1885

Answers (1)

chengpohi
chengpohi

Reputation: 14227

It should be:

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

For your question, you want to match a pattern of spaces, In Scala,

A regular expression is used to determine whether a string matches a pattern and, if it does, to extract or transform the parts that match.

for extracting match parts we need to use group to pattern a string. It means that we need to use parentheses to around our pattern string.

Example:

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

Upvotes: 10

Related Questions