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));

In reply to Help modifying recursive regex by beeflobill

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.