Replace all regex occurrences with item from array by index from regex group
I have text:
Lorem ipsum %NAME0% dolor sit amet %NAME1%, consectetur %NAME2% adipiscing elit.
and array names:
[Bob, Alice, Tom]
I need to get X index from %NAMEX% and replace all %NAME0%, %NAME1%, %NAME2% with corresponding item from array: names.get(X).
I have
private fun String.replaceWithNames(names: List): String {
var result = this
names.forEachIndexed { index, s ->
result = result.replace("%NAME$index%", s)
}
return result
}
but I am sure that it can be done...