This article explores different ways to remove non-alphanumeric characters from a string in Kotlin.

It is not possible to modify the contents of a string once it is created. This is because strings are immutable in Kotlin. To remove all non-alphanumeric characters from the string, you have to create a new string. This post provides an overview of several methods to accomplish this:

1. Using Regex.replace() function

You can use the regular expression [^a-zA-Z0-9] to identify non-alphanumeric characters in a string and replace them with an empty string. Use the regular expression [^a-zA-Z0-9 _] to allow spaces and underscore character.

Download Code

 
The word characters in ASCII are [a-zA-Z0-9_]. The regular expression \w and \W checks for the word and non-word character, respectively. Therefore, you can use the regular expression [^\w]* or [\W]* to identify non-alphanumeric characters in a string.

Download Code

2. Using String.replace() function

Alternatively, you can use the replace() function of the String class.

Download Code

3. Using filter() function

The filter() function returns all elements of the specified string that satisfies a certain predicate. To filter only alphanumeric characters, you can pass the isLetterOrDigit() to the filter() function, as demonstrated below:

Download Code

That’s all about removing non-alphanumeric characters from a string in Kotlin.