You may use a callback to String#replace() method and assign a variable inside it:
var needle = ""
val result = "Hello, world!".replace("world".toRegex()) { needle = it.value; "universe" }
println("Replacement result: " + result)
println("Found match: " + needle)
Result:
Replacement result: Hello, universe!
Found match: world
See the online Kotlin demo.
You may use a MutableList<String> to hold a list of matches and add the matches found to it:
var needle = mutableListOf<String>()
val result = "Hello, world! This world is too small.".replace("world".toRegex()) { needle.add(it.value); "universe" }
Result:
Replacement result: Hello, universe! This universe is too small.
Found match: [world, world]
See another Kotlin demo.