Arbitrarily nested structures cant be matched by proper regular expressions. Luckily perls regular expression engine isnt all that regular so it probably is possible to do this. (japhy knows how I'm sure.)

However it would be so much easier to do it with Text::Balanced or Parse::RecDescent that its unlikely anyone would try. Here is a solution using Text::Balanced

use Text::Balanced 'extract_tagged'; use Data::Dumper; sub get_ifs { my $str=shift; my $list=shift || []; my ($extracted, $remainder, $prefix, $open, $inside, $close)=extract_tagged($str,"IF","ENDIF","(?s).*?(?=IF)"); if ($extracted) { push @$list,$extracted; get_ifs($inside,$list); get_ifs($remainder,$list) if $remainder; } return $list; } print Dumper(get_ifs(<<ENDOFIFS)); IF(A) anytext IF(B) IF(C) anytext ENDIF IF(D) anytext ENDIF ENDIF ENDIF ENDOFIFS

In reply to Re: How to Extract Nested IF/THEN elements by demerphq
in thread How to Extract Nested IF/THEN elements by Al Shiferaw

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.