Menu
Coddy logo textTech

Finding and Replacing

Part of the Logic & Flow section of Coddy's Kotlin journey. Lesson 49 of 63.

Regex.findAll returns matches in order. Each match has a value string. You can iterate over these matches or transform them with map and collect them with toList. Regex.replace replaces every match with the specified replacement text.

Inside main:

val digits = Regex("[0-9]+")
println(digits.replace("Box12Shelf7", "#"))

Each consecutive digit group is one match, so there are two replacements.

findAll visits matches in order; Regex.replace replaces all matches by default.

challenge icon

Challenge

Medium

Complete extractNumbers with parameters text: String. Return every consecutive ASCII digit group as a string in left-to-right order. Preserve leading zeros. Return an empty list when there are no digits.

Unless stricter bounds are stated above, collections contain at most 100 elements at each level, and integer arguments and integer collection values are between -1000 and 1000. Text supplied for parsing can include invalid or out-of-range representations as described.

Return a value of type List<String>. Keep the supplied input/output code. It reads scalar arguments one per line; a list starts with its count followed by its elements, and a map starts with its entry count followed by each key and value. Nested lists repeat the count-and-elements format for each row. The supplied main prints the return value followed by one newline. Lists use Kotlin's standard bracketed format; print no additional labels.

Try it yourself

fun extractNumbers(text: String): List<String> {
    // Write your solution here.
    return emptyList()
}
fun main() {
    val text = readLine().orEmpty()
    println(extractNumbers(text))
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Kotlin playground