Library contents

Scala Regex extractors

A Scala Regex used as a pattern extractor normally matches the complete input and binds its capture groups.

A simple example

Regex extractors

  1. Start with "12" and the pattern ^[0-9]+$
  2. Do this Match the whole string
  3. Result Match
Both characters are digits, so the pattern covers the text from beginning to end.

Syntax

Scala syntax
case pattern(serial) => serial
Run this example in Scala

Save the program as Lesson.scala. Use Scala 2.13.

scalac Lesson.scala
scala Lesson

Validate a shipment label and keep its serial digits

A scanner imports labels written to a prescribed identifier format. Match the complete label and extract only the required fields so a valid-looking substring cannot admit a malformed shipment.

From the programval shipment = "PK-([0-9]{2})".r
First output line07
Lesson.scala
object Lesson {
  def main(args: Array[String]): Unit = {
    val shipment = "PK-([0-9]{2})".r
    for (label <- List("PK-07", "PK-07x", "PK-7")) {
      val result = label match {
        case shipment(serial) => serial
        case _ => "invalid"
      }
      println(result)
    }
  }
}
Output
07
invalid
invalid

Keeping the captured serial as a string preserves its leading zero. A suffix prevents a full match and routes the input to the fallback case.

Scala documentation for Regex extractors

Advertisements

Validate a sample label

A lab assistant scans a four-character sample code. The form accepts exactly two capital ASCII letters followed by two digits. Does the complete entry meet that rule?

GivenPH07
Worked resultAccept

Catch an extra digit

A clerk accidentally types one additional digit in a shelf code. The form accepts exactly two capital ASCII letters followed by two digits. Does the complete entry meet that rule?

GivenAR123
Worked resultReview