Objective:
Given a string of the form val strang = "ab(cde(fgh)ijk)lmn)opq)rs"
First I want to construct a vector of the string split by the "(" and ")" characters. This is accomplished with,
val regexPattern = "((?<=\\()|(?=\\())|((?<=\\))|(?=\\)))"
val data: Vector[String] = strang .split(regexPattern ).map(_.toString).toVector
Note that the actual string will be much more varied, but how it's split stands.
Secondly and this is the hard part that I need help with. I want to iterate over the data vector and construct a nested vector with the following logic (below is psudo-codish)
val newVector =
for(row <- data) {
if(row == "(") // opening angle bracket
start constructing a nested vector inside of newVector
keep appending to the nested vector until we encounter a ")"
character (closing parenthesis).
IF before encountering a ")" we encounter another "(" then
create another nestedVector inside the previous nested vector
and keep appending to it until a closing parenthesis ")" is
encountered
else if(row == ")")
if we encounter a closing parenthesis, go up one level of the nested
vectors
else
simply append this row to the new vector
newVector :+ row
}
I have made quite a few attempts at this with limited success. Using a recursive function I manage just one level of nesting but to go beyond that I end up using while loops which seems like overkill. The nested vectors can be of a special type. I have tried for example case class Rowy(row: String, rows: Vector[Vector[String]]) or case class Rowy(row: String, rows: Vector(Rowy))
I'm relatively new to scala and am wondering if there is an elegant way to approach this using scanLeft or foldLeft methods. Any help would be appreciated.
PS: I don't use an actual for loop to iterate over the "data" vector but rather a recursive function. The for loop is just to convey that an iteration is taking place. Any help would be appreciated.
Vector[Any], so you'll need a custom one and it might sense to tailor it to your usage scenario.<and>)."((?<=[()])|(?=[()]))"