代码之家  ›  专栏  ›  技术社区  ›  Jan Bodnar

Kotlin regex split-删除尾随空格

  •  2
  • Jan Bodnar  · 技术社区  · 6 年前

    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 回复  |  直到 6 年前
        1
  •  3
  •   Wiktor Stribiżew    6 年前

    空项出现在那里,因为您的字符串有一个非单词 . 最后是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+ :

    val pattern = """\w+""".toRegex()
    val words = pattern.findAll(text).map{it.value}.toList()
    // => [I, saw, a, fox, in, the, wood, The, fox, had, red, fur]
    
        2
  •  0
  •   user8959091 user8959091    6 年前

    您可以删除最后一项:

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