CodeBlanks Logo Icon CodeBlanks

replace

Learn replacement with replace and lambda.

replace: swap matched parts

replace replaces every part that matches the pattern with a new string. The first argument is a Regex, the second is the replacement text.

val r = Regex("\\d+")
val result = "a1b22c".replace(r, "#")
// "a#b#c"

To swap digits with # you write the pattern once. replace scans every match in order and puts the new text in its place. Use replaceFirst to replace only the first match.

replace with a lambda: flexible transform

You can transform each match separately by passing a lambda. The lambda takes a MatchResult and returns the replacement string.

val r = Regex("\\w+")
val result = "hello world".replace(r) {
    it.value.replaceFirstChar { c -> c.uppercaseChar() }
}
// "Hello World"

To capitalise the first letter of each word, use replaceFirstChar. Pick the lambda form when you want a transform, not a fixed text. This lets you shape the whole string in one pass.

Practice Replace digits with #

With Regex("\\d+"), replace the digits in "a1b22c333" with "#"; print the result.

Starter code

Main.kt
fun main() {
    val r = Regex("\\d+")
    // Use replace to turn digits into diyez and print
}

Sample solution

Main.kt
val r = Regex("\\d+")
println("a1b22c333".replace(r, "#"))

Expected output

a#b#c

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Fill in the blank: replace digits

Question
val r = Regex("\\d+")
val result = "a1b2".____(r, "#")
Answer
val r = Regex("\\d+")
val result = "a1b2".replace(r, "#")

Explanation: replace swaps every match with the given text.

2 What does replace(r) { ... } do?

  • Replace with fixed text
  • Transform instead of fixed text Correct answer
  • Find the first match
  • Count all matches

Explanation: The lambda transforms each match into a different string.

3 Match method to outcome

Term Meaning
replace(r, "#") All with fixed
replace(r) { ... } Transform per match
replaceFirst(r, "#") Only the first
matches Does all fit

All lessons in Beginner