Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string by repeatable delimiter in Java/Kotlin

Tags:

java

regex

kotlin

I am splitting a string by a repeatable delimiter, and am also intended to keep the delimiters as well.

val str = "xxoooooooxxoxoxooooo"
val reg = Regex("(?<=x+)|(?=x+)")
var list = str.split(reg)
println(list) 

The output is [, x, x, ooooooo, x, x, o, x, o, x, ooooo], though I would like to get

[xx, ooooooo, xx, o, x, o, x, ooooo]

like image 344
Mark Avatar asked Dec 31 '22 19:12

Mark


1 Answers

val str = "xxoooooooxxoxoxooooo"
val reg =  Regex("o+|x+").findAll(str).map { it.value }.toList()
println(reg)
//[xx, ooooooo, xx, o, x, o, x, ooooo]
like image 163
user2424380 Avatar answered Jan 04 '23 22:01

user2424380