Scala Language Pattern Matching Pattern Matching with Regex

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

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

"[email protected]" 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.



Got any Scala Language Question?