Scala String.matches
Validate a whole classroom code with one capital ASCII letter and two digits.
A simple example
String.matches
- Start with "12" and the pattern ^[0-9]+$
- Do this Match the whole string
- Result Match
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 LessonAccept 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.
object Lesson {
def main(args: Array[String]): Unit = {
val value = "B12"
println(if (value.matches("[A-Z][0-9]{2}")) "yes" else "no")
}
}
yes
All three characters meet the pattern.
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.
object Lesson {
def main(args: Array[String]): Unit = {
val value = "B12x"
println(if (value.matches("[A-Z][0-9]{2}")) "yes" else "no")
}
}
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?
What to watch for
Some regex APIs search for an occurrence. Use a full-match API or explicit whole-input anchors.