Library contents

Scala String.matches

Validate a whole classroom code with one capital ASCII letter and two digits.

A simple example

String.matches

  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
value.matches("[A-Z][0-9]{2}")
Run these examples in Scala

Save one example at a time as Lesson.scala. Use Scala 2.13 on JDK 21.

scalac Lesson.scala
scala Lesson

Accept a printed seat identifier

An exam supervisor scans a printed seat code. Accept a label that follows the required letter-and-digit pattern; the scanner must consume the entire code before confirming the seat.

From the programval value = "B12"
Resultyes
Lesson.scala
object Lesson {
    def main(args: Array[String]): Unit = {
        val value = "B12"
        println(if (value.matches("[A-Z][0-9]{2}")) "yes" else "no")
    }
}
Output
yes

All three characters meet the pattern.

Advertisements

Reject a seat code with a suffix

A classroom scanner expects a seat identifier in a specific format. Validate the whole field so an otherwise valid prefix cannot admit stray characters at the end.

From the programval value = "B12x"
Resultno
Lesson.scala
object Lesson {
    def main(args: Array[String]): Unit = {
        val value = "B12x"
        println(if (value.matches("[A-Z][0-9]{2}")) "yes" else "no")
    }
}
Output
no

The extra letter is outside the allowed format.

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

What to watch for

Some regex APIs search for an occurrence. Use a full-match API or explicit whole-input anchors.

Documentation for String.matches