It kinda looks like your parsing XML, so why not use an XML parser, such as XML::Simple? That way you are presented with a Perl data structure you can traverse rather than trying to craft a regex which is quite possibly slower and has far more potential for errors.