I would approach the problem this way:

c:\@Work\Perl>perl -wMstrict -le "use Test::More 'no_plan'; use Test::NoWarnings; ;; my $metadata = qr{ < [^>]* > }xms; ;; for my $ar_vector ( [ 'somewordaa<metadata><moremetadata>r another wo<metadata>rd', 'somewordaa<metadata><moremetadata>r another wo<metadata>rd', ], [ 'aword<metadata>aa<metadata> another wo<metadata>rd', 'aword<metadata>a<metadata> another wo<metadata>rd', ], [ 'wor<metadata>dsandmor<metadata>ewordsaa<metadata>', 'wor<metadata>dsandmor<metadata>ewordsa<metadata>', ], ) { my ($s, $expected) = @$ar_vector; $s =~ s{ aa (?! $metadata* r) }{a}xmsg; is $s, $expected, qq{'$expected'}; } " ok 1 - 'somewordaa<metadata><moremetadata>r another wo<metadata>rd' ok 2 - 'aword<metadata>a<metadata> another wo<metadata>rd' ok 3 - 'wor<metadata>dsandmor<metadata>ewordsa<metadata>' ok 4 - no warnings 1..4
Note that making the character class match 'atomic' or possessive may speed things up a bit for large data (for some definition of 'large') by suppressing backtracking on subsequent match failure:
    my $metadata = qr{ < (?> [^>]*) > }xms;
and for Perl version 5.10 and above:
    my $metadata = qr{ < [^>]*+ > }xms;
(both variations tested). Your data will determine if possessiveness actually makes a difference. The regex compiler may be smart enough to make this optimization on its own (I haven't checked), but giving the compiler a hint never hurts.

And of course, you will want to add many more test cases!


In reply to Re^3: Regex question - capturing next char by AnomalousMonk
in thread Regex question - capturing next char by perluser4102

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.