I want to find an efficient way to select all the sub-strings contained in the first group of nested parentheses from a string.
For example:
input: a d f gsds ( adsd ) adsdaa
output: ( adsd )
input: adadsa ( sadad adsads ( adsda ) dsadsa ) ( dsadsad )
output: ( sadad adsads ( adsda ) dsadsa )
intput: a ana anan anan ( adad ( sad ) sdada asdad ) ( sadad ( adasd ) asda ) sdafds ( afdasf )
output: ( adad ( sad ) sdada asdad )
Notice there could be multiple groups of nested parentheses.
One solution would be scanning the string char
by char
and keeping track of the number of opened parentheses until (decreasing the number, once we have a closing parenthesis) the counter becomes 0 again.
I am wondering if there is a simpler way to do it? Maybe with regular expressions?
Thanks