Library contents

Kotlin Regex.matches

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

A simple example

Regex.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

Kotlin syntax
Regex("[A-Z][0-9]{2}").matches(value)
Run these examples in Kotlin

Save one example at a time as Lesson.kt. Use Kotlin 2.2 on JDK 21.

kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jar

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.kt
fun main() {
    val value = "B12"
    println(if (Regex("[A-Z][0-9]{2}").matches(value)) "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.kt
fun main() {
    val value = "B12x"
    println(if (Regex("[A-Z][0-9]{2}").matches(value)) "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 Regex.matches