Scala Language Pattern Matching Pattern Matching with Regex


val emailRegex: Regex = "(.+)@(.+)\\.(.+)".r

"" match {
  case emailRegex(userName, domain, topDomain) => println(s"Hi $userName from $domain")
  case _ => println(s"This is not a valid email.")

In this example, the regex attempts to match the email address provided. If it does, the userName and domain is extracted and printed. topDomain is also extracted, but nothing is done with it in this example. Calling .r on a String str is equivalent to new Regex(str). The r function is available via an implicit conversion.