Ant's Ant's - 2 days ago 3
Groovy Question

How I can find the contents of inner nesting?

Lets say I have a string like this :

string = [+++[>>[--]]]abced


Now I want a someway to return a list that has:
[[--],[>>],[+++]]
. That is the contents of the deepest
[
nesting followed by other nesting. I came up with this solution like this :

def string = "[+++[>>[--]]]"
loop = []
temp = []
string.each {
bool = false
if(it == "["){
temp = []
bool = true
}
else if( it != "]")
temp << it
if(bool)
loop << temp

}
println loop.reverse()


But this indeed takes the
abced
string after the last
]
and put into the result!. But what I want is only
[[--],[>>],[+++]]


Are there any groovy way of solving this?

Answer

You can use this, if you wouldn't mind using recursion

def sub(s , list){
    if(!s.contains('[') && !s.contains('[')) 
        return list
    def clipped = s.substring(s.lastIndexOf('[')+1, s.indexOf(']'))
    list.add(clipped)
    s = s - "[$clipped]"
    sub(s , list)
}

Calling

sub('''[+++[>>[--]]]abced''' , [])

returns a list of all subportions enclosed between braces.

['--', '>>', '+++']
Comments