Skip to content
Advertisement

How do I replace multiple characters in a String?

How do I replace multiple characters in a String?

Like Java’s replaceAll(regex:replacement:) function.

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

This answer is very close but I want to change more than one character at the same time.

Advertisement

Answer

[$,.] 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.

Advertisement