as said above, if you have any control over the format of this data you should get it changed to either an easier to parse proprietary format or get it into valid xml. As it stands a full xml parser wouldn't touch it with a barge poll (and rightly so)

having said that, you could approach your regex from the other end and work backwards. I think this does what you want.

while ( $content =~ s/(.*<level1 id="([^"]*).*?)<level2>/$1<level2 id= +\"$2\">/gsi ) { }
I feel dirty just posting that though, as it's so flaky a single white space would break it. Think of it as an example as to why you should fix your file format :)

UPDATE

I couldn't shake the feeling inflicted on myself by the above post. I seek to redeem myself with a full xml version :)

#!/usr/bin/perl use XML::DOM; use warnings; use strict; my $xml = q|<root> <level1 id="L1_0001"> <level2> <level3> <level4/> </level3> <level3> <level4/> </level3> </level2> <level2/> </level1> <level1 id="L1_0002"> </level1> <level1 id="L1_0003"> <level2> <level3/> </level2> </level1> </root>|; my $parser = new XML::DOM::Parser; my $doc = $parser->parse($xml); foreach my $l1_node ($doc->getElementsByTagName ('level1') ) { my $current_id = $l1_node->getAttribute('id'); foreach my $l2_node ($l1_node->getElementsByTagName ('level2') ) { $l2_node->setAttribute('id', $current_id); } } print $doc->toString; exit();
---
my name's not Keith, and I'm not reasonable.

In reply to Re: Regex problem while parsing tagged, hierarchical data by reasonablekeith
in thread Regex problem while parsing tagged, hierarchical data by sivaramanm

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.