Kotlin Split Sentence String Into Words

May 18, 2019
val text = "I'm home, baby 小米."
val words = text.split("\\s+".toRegex()).map { word ->
    word.replace("""^[,\.]|[,\.]$""".toRegex(), "")
}

Result

["I'm", "home", "baby", "小米"]

Option 2

val words = text.split("\\P{L}+".toRegex())

Result

["I", "m", "home", "baby", "小米", ""]

Option 3

val words = text.split("\\s+".toRegex())

Result

["I'm", "home", "", "baby", "小米."]

Option 4

val words = text.split("\\W+".toRegex())

Result

["I", "m", "home", "baby", ""]
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.