You'll want to think about recursion - a function that can call itself.
Your regular expression is doing its job in finding exactly what you are looking for, but as you noticed, it works in a linear fashion, not in an embedded fashion.
You might want to think about finding the first if, and...