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:

Download Code

 
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 _.

Download Code

 
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]|_.

Download Code

 
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].

Download Code

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.

Download Code

3. Using filter() function

Finally, we can filter out the characters that don’t match with the Char.isLetterOrDigit() function. This is demonstrated below:

Download Code

That’s all about removing all alphabets and numbers characters from a String in Kotlin.