http://www.perlmonks.org?node_id=1032522

beeflobill has asked for the wisdom of the Perl Monks concerning the following question:

A long time ago I worked really hard and wrote a piece of recursive regex code which I'm trying to modify now. It takes text with nested parentheses and returns a list with the "top" groups of parentheses.

Here is an example which shows what the regex does:
Input: "A (B C D)"
Output: "B C D"

Input: "A (B C D) (E F G)"
Output: "B C D", "E F G"

Input: "A B (C (D E) (F G)) (H I)"
Output: "C (D E) (F G)", "H I"

Even when I wrote the code I knew I would really, really want to keep the data that wasn't in parentheses too, but I couldn't figure out how to do it. Now I'm back on the problem.

Here is an example of what I am trying to get:
Input: "A (B C D)"
Output: "A", "B C D"

Input: "A (B C D) (E F G)"
Output: "A", "B C D", "E F G"

Input: "A B (C (D E) (F G)) (H I)"
Output: "A", "B", "C (D E) (F G)", "H I"

I still don't know how to do that. I've provided a test script demonstrating the subroutine that does what I'm describing. May I supplicate, how might I modify this to do what I need? Or, is there simply a better way to approach this problem? Thanks.

#!/usr/bin/perl -w use strict; sub strip_paren { my $input = $_[0]; my $re; $re = qr/ (?: \( ( (?: [^()]+ | (??{$re}) )+ ) \) ) | \(\) /x; my @output = $input =~ /$re/g; return @output; } sub print_crud { print shift, "\n"; foreach my $line (@_) { print " $line\n"; } print "\n"; } my $string = "A (B C D)"; print_crud($string, strip_paren($string)); $string = "A (B C D) (E F G)"; print_crud($string, strip_paren($string)); $string = "A B (C (D E) (F G)) (H I)"; print_crud($string, strip_paren($string));