Home > Back-end >  Splitting string with "\\s".toRegex() is not working in Kotlin
Splitting string with "\\s".toRegex() is not working in Kotlin

Time:10-28

I have tried using "\\s".toRegex() in the following way.

var sentence = "test1    test2   test3"
sentence.split("\\s".toRegex()) 

It splits the string into more than 3 items(since there are spaces). But I would like the string to be divided into 3 items by not considering space.

I tried the same with sentence.split(" ".toRegex()) it is working as expected and returning 3 items [Test1,test2,test3]

Why "\\s".toRegex() is not working?

CodePudding user response:

for one or more matches you need to add the , just like you did with " " so if you want to use \\s you also add the plus like

sentence.split("\\s ".toRegex())

  • Related