/ scala

TOTD: Scala - Regex Pattern Matching

Today we'll look at how to match regex groups using pattern matching. Suppose we have the following two literal strings that are turned into a Regex instance (by calling r on it via a typeclass).

val pattern2 = """(\d+)""".r

The first pattern has two groups, while pattern2 has a single group.

Next, we define a method that pattern matches on some input using our regex patterns above.

def extract(n: String) = n match {
  case pattern1(g1, g2) => println(s"pattern1: g1($g1) - g2($g2)")
  case pattern2(g) => println(s"pattern2: $g")
  case _ => println("No match!")
}

Now let's give it some input:

extract("123-467")
extract("123567")
extract("abcdefg")

Notice how we unpack the groups in each case and how they correspond to how we wrote each Regex pattern. Try this out in your a Scala REPL near you!