Remove punctuation from a string in Kotlin
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.
|
1 2 3 4 5 6 7 8 9 |
fun removePunctuations(source: String): String { return source.replace("\\p{Punct}".toRegex(), "") } fun main() { var source = "(A,B)#C:{A_B}[D]" source = removePunctuations(source) println(source) // ABCABD } |
The punctuation class matches with the characters !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~. We can also directly add or remove the desired characters from it.
|
1 2 3 4 5 6 7 8 9 |
fun removePunctuations(source: String): String { return source.replace("[!\"#$%&'()*+,-./:;<=>?@\\[\\]^_`{|}~]".toRegex(), "") } fun main() { var source = "(A,B)#C:::{A_B}[D]" source = removePunctuations(source) println(source) // ABCABD } |
We can easily add another POSIX class to the regex, as shown below:
|
1 2 3 4 5 6 7 8 9 |
fun removePunctuations(source: String): String { return source.replace("\\p{Punct}|\\p{Space}".toRegex(), "") } fun main() { var source = "(A,B)#C: {A_B}[D]" source = removePunctuations(source) println(source) // ABCABD } |
If the replace() function is frequently invoked, consider compiling the regular expression to get better performance. This can be implemented as follows in Kotlin.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import java.util.regex.Pattern private val PUNCT_SYMBOLS = Pattern.compile("[!\"#$%&'()*+,-./:;<=>?@\\[\\]^_`{|}~]") fun removePunctuations(source: String?): String { return PUNCT_SYMBOLS.matcher(source).replaceAll("") } fun main() { var source = "(A,B)#C:::{A_B}[D]" source = removePunctuations(source) println(source) // ABCABD } |
That’s all about removing punctuation 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 :)