Dear fellow monks,

I have a regex question. It is not a real problem, I'm just curious if it is possible at all:

It's about (non)greediness, left to right and regex replacements.

Before I post the code, I need to let you know that

  1. yes, I know that HTML code should not be parsed with regexes
  2. I only came across this problem when trying to solve this for someone else, but the regex question also applies to other examples

#!/usr/bin/perl use strict; use warnings; my $string =<<'EOF'; <tr> <td>aaa</td> <td>aaa</td> </tr> <tr> <td>NOTWANTED</td> </tr> <tr> <td>bbb</td> <td>bbb</td> </tr> EOF # try to remove all table rows with NOTWANTED $string =~ s/<tr.+?NOTWANTED.+?<\/tr>//gsm; print $string;

prints only the third table row. As far as I understand, the problem here is that regex starts with the leftmost "<tr" (the first one) and will find a (smallest) match that contains NOTWANTED and will remove it.

While this problem can easily be solved with
my @tr = split(/(?=<tr)/, $string); # split at <tr, but do not remove +<tr @tr = grep { ! /NOTWANTED/ } @tr; # remove the elements with NOTWANT +ED print join('', @tr);
I'm still curious if it can be done with a regex replacement.
Waiting for your comments,
svenXY

In reply to greedy/nongreedy regex replacement by svenXY

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.