Library contents

Kotlin Regex.replaceFirst

Replace just the first run of digits when updating the first field on a label.

A simple example

Regex.replaceFirst

  1. Start with "a1b2"
  2. Do this Replace only the first digit with *
  3. Result "a*b2"
The search stops replacing after the 1. The final 2 remains.

Syntax

Kotlin syntax
Regex("[0-9]+").replaceFirst(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

Mask just the first locker number

A service desk displays an identifier where bystanders could see it. Replace the intended numeric field or digit runs while preserving the rest of the record for the operator.

From the programval value = "B12 / C34"
ResultB* / C34
Lesson.kt
fun main() {
    val value = "B12 / C34"
    println(Regex("[0-9]+").replaceFirst(value, "*"))
}
Output
B* / C34

The second number stays visible.

Advertisements

Handle a label without a number

A booking or stock form receives text where the program expects a quantity. Decide what to do with missing, malformed or out-of-range input before using the parsed value in a transaction.

From the programval value = "Library"
ResultLibrary
Lesson.kt
fun main() {
    val value = "Library"
    println(Regex("[0-9]+").replaceFirst(value, "*"))
}
Output
Library

With no digit match the label stays the same.

Mask a public job number

A noticeboard shows the department prefix and hides the serial. The editor replaces a matching run of digits with a single star before sharing the label. Each sample has one numeric run.

GivenART-184 → replace digits
Worked resultART-*

What to watch for

Replacement syntax differs between regex engines. Use a literal replacement when punctuation must be matched exactly.

Documentation for Regex.replaceFirst