Kotlin正则表达式拆分-删除尾部空间

时间:2018-08-22 10:57:46

标签: regex kotlin

在科特林,我把一个句子分成单词。 split方法在列表末尾添加一个空格。如何摆脱尾随的空间? 有没有创建新列表的简单方法?

package com.zetcode

fun main(args: Array<String>) {

    val text = "I saw a fox in the wood. The fox had red fur."

    val pattern = "\\W+".toRegex()

    val words = pattern.split(text)

    println(words)
}

该示例显示[I, saw, a, fox, in, the, wood, The, fox, had, red, fur, ]

2 个答案:

答案 0 :(得分:3)

此处显示空项,因为您的字符串末尾有一个非单词infoLabel char。您可能只是省略了空项目以解决问题:

.

或者,使用与val text = "I saw a fox in the wood. The fox had red fur." val pattern = """\W+""".toRegex() val words = pattern.split(text).filter { it.isNotBlank() } println(words) // => [I, saw, a, fox, in, the, wood, The, fox, had, red, fur] 相反的模式的匹配方法:

\w+

答案 1 :(得分:0)

您可以删除最后一项:

val words = pattern.split(text).dropLastWhile { it == "" }