Remove non-alphanumeric characters from a string in Kotlin
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.
|
1 2 3 4 5 6 7 8 |
fun main() { val s = "Test@@String#123" val regex = Regex("[^A-Za-z0-9]") val result = regex.replace(s, "") println(result) // TestString123 } |
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.
|
1 2 3 4 5 6 7 8 |
fun main() { val s = "Test@@String#123" val regex = Regex("[^\\w]") val result = regex.replace(s, "") println(result) // TestString123 } |
2. Using String.replace() function
Alternatively, you can use the replace() function of the String class.
|
1 2 3 4 5 6 7 |
fun main() { val s = "Test@@String#123" val result = s.replace(("[^\\w]").toRegex(), "") println(result) // TestString123 } |
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:
|
1 2 3 4 5 6 7 |
fun main() { val s = "Test@@String#123" val result = s.filter { it.isLetterOrDigit() } println(result) // TestString123 } |
That’s all about removing non-alphanumeric characters from a string in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)