Both of those regexps fail when 'b' isn't the last character in the string, because the negative lookahead assertion is zero-width, and yet you're anchoring to the RHS of the string.

Look at the following code and you'll see:

use strict; use warnings; my $orig_string = 'abababa'; my @tests = ( qr/(b)(?!.*b)$/ , qr/b(?!.*b)$/ , qr/b(?!.*b.*$)/ , qr/b(?=[^b]*$)/ ); foreach my $test_re ( @tests ) { my $scratch = $orig_string; print "$test_re\tdid", $scratch =~s/$test_re/x/ ? ' ' : "n't " , "match '$orig_string', yielding '$scratch'\n"; }

The problem with your regexps is that they require 'b' to be the last thing in the string. This is because the lookahead assertion, positive or negative, is zero-width. If you move the anchor inside the assertion, it would improve, but it becomes kludgy, and IMO, not as clearly defined if you insist on using negative lookahead (see the third test regexp). In the fourth regexp, you can see the use of a positive lookahead and a negated character class, which, to me, is clearer, harder to break, etc.


Dave


In reply to Re^3: RE - match from right by davido
in thread RE - match from right by bangers

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.