sub indexBal { my( $string, $lookFor, $limit ) = @_; my $nesting = 0; for( my( $position, $char ) = ( 0, substr $string, 0, 1 ); $position < min( length( $string ) , $limit ); $char = substr $string, ++$position, 1 ) { $nesting++ if $char =~ m/[\[\{]/; $nesting-- if $char =~ m/[\]\}]/; die 'Unbalanced' if $nesting < 0; return $position if $char eq $lookFor and $nesting == 0 } return; } my $s = '{ [ { [ { x }, { y } ], [ z ] } ] } { [ { '; my $pos = indexBal $s, '}', length( $s ); print substr $s, 0, $pos+1; { [ { [ { x }, { y } ], [ z ] } ] }