This article explores different ways to remove given characters from a string in Kotlin.

The replace() function replaces each substring of a string that matches the given regular expression. It can be used to return a new string without the specified characters (since strings are immutable). For instance, consider the following code that will replace all matches of the regular expression \w with an empty string. Here, \w matches with the word character set [a-zA-Z_0-9].

Download Code

 
We can retain specific characters using negation ^. For example, [^a-zA-Z] matches with all characters except ASCII alphabets.

Download Code

 
Here’s another variation that uses the overloaded version of the replace() function to remove all occurrences of the specified characters from the string.

Download Code

That’s all about removing given characters from a string in Kotlin.