Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split a string according to repeating regular expression in Scala

Tags:

regex

scala

In Scala I have a string of the form

val str = "[ab][bc][cd][dx][42]"

What is the most efficient way in Scala, regular expression utilizing or otherwise, to split that string into a Seq[String] that would be of the form:

("ab","bc","cd","dx","42")

Thank you.

like image 865
Ramón J Romero y Vigil Avatar asked Mar 15 '26 03:03

Ramón J Romero y Vigil


2 Answers

You can try this:

val str = "[ab][bc][cd][dx][42]"
val res = str.drop(1).sliding(2, 4).toList
println(res) // List(ab, bc, cd, dx, 42)

val str2 = "[ab]"
val res2 = str2.drop(1).sliding(2, 4).toList
println(res2) // List(ab)

val str3 = ""
val res3 = str3.drop(1).sliding(2, 4).toList
println(res3) // List()
like image 132
user5102379 Avatar answered Mar 16 '26 15:03

user5102379


you can try:

str.split("(\\]\\[)|(\\[)|(\\])").filterNot(_.isEmpty)

Mainly using groups (][, ], [) for delimiter and trimming the array.

like image 23
nitishagar Avatar answered Mar 16 '26 17:03

nitishagar