Remove all alphabets and numbers from a String in Kotlin
This article explores different ways to remove all alphabets and numbers from a String in Kotlin.
1. Using CharSequence.replace() function
The idea is to use the regular expression to remove all alphabets and numbers from a String. The regular expression [^A-Za-z0-9] can be used to retain only ASCII alphabets and numbers in the string, as demonstrated below with the replace() function:
|
1 2 3 4 5 6 7 8 |
fun removeNonAlphaNumChars(s: String?): String? { return s?.replace("[^A-Za-z0-9]".toRegex(), "") } fun main() { val s = "(A)B,C|D_1" println(removeNonAlphaNumChars(s)) // ABCD } |
The regular expression [^\w] is equivalent to [^a-zA-Z0-9_] which matches with all characters not present in the character range [A-Z], [a-z], [0-9], and underscore _.
|
1 2 3 4 5 6 7 8 |
fun removeNonAlphaNumChars(s: String?): String? { return s?.replace("[^\\w]".toRegex(), "") } fun main() { val s = "(A)B,C|D_1" println(removeNonAlphaNumChars(s)) // ABCD_1 } |
This is equivalent to \W which directly matches with any non-word character, i.e., [a-zA-Z_0-9]. To remove underscore as well, use regex [\W]|_.
|
1 2 3 4 5 6 7 8 |
fun removeNonAlphaNumChars(s: String?): String? { return s?.replace("[\\W]+".toRegex(), "") } fun main() { val s = "(A)B,C|D_1" println(removeNonAlphaNumChars(s)) // ABCD_1 } |
Alternatively, we can use the POSIX character class \p{Alnum}, which is equivalent to [\p{Alpha}\p{Digit}], and matches with any alphanumeric character [A-Za-z0-9].
|
1 2 3 4 5 6 7 8 |
fun removeNonAlphaNumChars(s: String?): String? { return s?.replace("[^\\p{Alnum}]".toRegex(), "") } fun main() { val s = "(A)B,C|D_1" println(removeNonAlphaNumChars(s)) // ABCD } |
2. Using Regex.replace() function
The Regex class also provides a replace() function, that replaces all occurrences of the regular expression in the specified string with the specified replacement.
|
1 2 3 4 5 6 7 8 |
fun removeNonAlphaNumChars(s: String): String? { return Regex("[^A-Za-z0-9]").replace(s, "") } fun main() { val s = "(A)B,C|D_1" println(removeNonAlphaNumChars(s)) // ABCD } |
3. Using filter() function
Finally, we can filter out the characters that don’t match with the Char.isLetterOrDigit() function. This is demonstrated below:
|
1 2 3 4 5 6 7 8 |
fun removeNonAlphaNumChars(s: String): String? { return s.filter { it.isLetterOrDigit() } } fun main() { val s = "(A)B,C|D_1" println(removeNonAlphaNumChars(s)) // ABCD } |
That’s all about removing all alphabets and numbers 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 :)