https://kotlinlang.org logo
z

zt

10/04/2022, 12:55 AM
Copy code
val values = match.groupValues.drop(1) // ["kotlin slack"]
var newResponse = filter.response!! // "hi $1"
values.forEachIndexed { index, value ->
    newResponse = filter.response!!.replace("\$$index", value)
}

// newResponse = "hi kotlin slack"
Is there some cleaner way of doing this? I wanna replace
$0
,
$1
,
$2
, etc, with its corresponding value
e

ephemient

10/04/2022, 1:45 AM
Copy code
repsonse.replace("\$([0-9])".toRegex()) { match ->
    values[match.group(1).toInt()]
}
m

Michael de Kaste

10/04/2022, 9:26 AM
you can also use java's built-in formatting:
Copy code
"hi $3, $1 and $2"
    .replace("""\$(\d+)""".toRegex()) { "%${it.groupValues[1]}\$s" }
    .format("tom", "alice", "bob")

// hi bob, tom and alice
e

ephemient

10/04/2022, 9:43 AM
only if you can guarantee there's no
%
in the original string
m

Michael de Kaste

10/04/2022, 9:47 AM
perhaps OP manages the "filter.response" callsite so he can just do string formatting to begin with