Scala FAQ: How do I perform pattern matching on a regular expression string in a match
expression?
Using Scala 3, I was just trying to perform some pattern matching on a regular expression (regex) string in a match
expression, and while working with ChatGPT, I came up with this solution, which you can easily verify in the Scala REPL:
import scala.util.matching.Regex // define a regular expression pattern val EmailPattern: Regex = "([a-zA-Z0-9._-]+)@([a-zA-Z0-9.-]+)\\.([a-zA-Z]{2,4})".r def matchString(input: String): String = input match case "hello" => "You said hello!" case "goodbye" => "You said goodbye!" // use the regex pattern here case EmailPattern(username, domain, tld) => s"Email found with username: $username, domain: $domain, top-level domain: $tld" case _ => "No match found" println(matchString("hello")) println(matchString("goodbye")) println(matchString("user@example.com")) println(matchString("123"))
All of those expressions work, including the EmailPattern
, which has the Regex
type. A cool thing about this solution is that the three regex pattern groups in the Regex
pattern can be used just like constructor parameters that are passed into EmailPattern
, even though no such parameters are declared.
There may be other ways to declare EmailPattern
, but I haven’t looked into that yet, because this solution works for my current needs.
In summary, if you want to perform regex pattern matching in a Scala match
expression, I hope this example is helpful.