This article explores different ways to remove punctuation from a string in Kotlin.

The replace() function removes each substring of the char sequence that matches the given regular expression. We can either use the POSIX class \p{Punct} or predefined punctuation class p{IsPunctuation} for creating a regular expression that matches with the ASCII punctuation characters.

Download Code

 
The punctuation class matches with the characters !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~. We can also directly add or remove the desired characters from it.

Download Code

 
We can easily add another POSIX class to the regex, as shown below:

Download Code

 
If the replace() function is frequently invoked, consider compiling the regular expression to get better performance. This can be implemented as follows in Kotlin.

Download Code

That’s all about removing punctuation from a string in Kotlin.