Kotlin program to remove special characters from a string

Introduction :

In this tutorial, we will learn how to remove all special characters from a string in Kotlin. Our program will remove all non-alphanumeric characters excluding space. For example, if the string is abc 123 *&^, it will print abc 123.

I will show two different ways to solve it in Kotlin. Just try to run the sample programs with different strings.

Method 1: Using regex :

regex or regular expression is a sequence of characters used to match characters in a string. We can use the below regular expression :

[^A-Za-z0-9 ]

It will match all characters that are not in between A to Z and not in between a to z and not in between 0 to 9 and not a blank space. Then we will simply replace those characters with an empty character.

fun main() {
    var str = "Hello !!!๐Ÿ˜Žworld @1233*@@():)๐Ÿ‘Œ๐Ÿ‘Œ๐Ÿ‘Œ"

    val re = "[^A-Za-z0-9 ]".toRegex()
    str = re.replace(str, "")


It will print the below output :

Hello world 1233

toRegex() method is used to convert one string to a regular expression. replace method is used to replace all characters matched by that regex with empty space.

Kotlin remove special characters from string regex

Method 2: Using filter :

filter is another way to remove unwanted characters from a string. It takes one predicate and returns a string containing only those characters from the original string that matches the predicate. Below is the complete program :

fun main() {
    var str = "Hello !!!๐Ÿ˜Žworld @1233*@@():)๐Ÿ‘Œ๐Ÿ‘Œ๐Ÿ‘Œ"

    str = str.filter{ it.isLetterOrDigit() || it.isWhitespace() }


We are checking if the character is a letter or digit or whitespace or not. The final result is the same as the above example.

Kotlin remove special characters from string filter

Where is the color and why codevscolor ?

Long story short, I love paintings and I paint on weekends. We(me and my wife) have one Youtube channel. Below is a video that I did recently. If you love this please do subscribe to support us ๐Ÿ˜Š