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
- Start with "12" and the pattern ^[0-9]+$
- Do this Match the whole string
- Result Match
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.
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)
}
}
}
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
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?
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?