Kotlin:尝试在多个空间上拆分时出现奇怪的行为

时间:2019-03-07 12:00:59

标签: string kotlin read-eval-print-loop

我想在多个空格上分割一个字符串。

我这样尝试过:

val s = "aa        q"

val words = s.split("\\s+").also { println(it) } //prints an array with the original string itself (as opposed to 2 strings)

println(words.size) //prints 1 

如果在Java中使用相同的正则表达式对字符串进行分割,则会得到预期的结果:一个包含两个字符串"aa""q"的数组

(这是在intellij的Kotlin repl上尝试的)

1 个答案:

答案 0 :(得分:2)

尝试使用 toRegex() toPattern()

val s = "aa        q"

val words = s.split("\\s+".toRegex()).also { println(it) } // print [aa, q]

println(words.size) //prints 2 

这是 link to kotlin描述功能的地方

@Test
fun useRegex() {
    //given
    val s = "aa       q"
    //when
    val words = s.split("\\s+".toRegex()).also { println(it) }  // print [aa, q]
    //then
    assertEquals(2, words.size)
    assertEquals("aa", words[0])
    assertEquals("q", words[1])
}

@Test
fun usePattern() {
    //given
    val s = "aa       q"
    //when
    val words = s.split("\\s+".toPattern()).also { println(it) } // print [aa, q]
    //then
    assertEquals(2, words.size)
    assertEquals("aa", words[0])
    assertEquals("q", words[1])
}



@Test
fun useDelimiters() {
    //given
    val s = "aa       q"
    //when
    val words = s.split("\\s+").also { println(it) }  // you find \s+ this is not regexp this is string not found then return [aa       q]
    val words2 = s.split("       ").also { println(it) }  // you must use correctly  number of spaces print [aa, q]
    //then
    assertEquals(1, words.size)
    assertEquals("aa       q", words[0])
    assertEquals(s, words[0])

    assertEquals(2, words2.size)
    assertEquals("aa", words2[0])
    assertEquals("q", words2[1])
}