Skip to content

Kotlin replace multiple characters all in string

How to replace multiple characters in kotlin string?

Like java replaceAll() function.

str.replaceAll("[$,.]", "") //java code

I know this answer so close but want to change more than one character at the same time



[$,.] is regex, which is the expected input for Java’s replaceAll() method. Kotlin, however, has a class called Regex, and string.replace() is overloaded to take either a String or a Regex argument.

So you have to call .toRegex() explicitly, otherwise it thinks you want to replace the String literal [$,.]. It’s also worth mentioning that $ in Kotlin is used with String templates, meaning in regular strings you have to escape it using a backslash. Kotlin supports raw Strings (marked by three " instead of one) which don’t need to have these escaped, meaning you can do this:

str = str.replace("""[$,.]""".toRegex(), "")

In general, you need a Regex object. Aside using toRegex() (which may or may not be syntactical sugar), you can also create a Regex object by using the constructor for the class:

str = str.replace(Regex("""[$,.]"""), "")

Both these signal that your string is regex, and makes sure the right replace() is used.

10 People found this is helpful