Well, if you read the comments there, we start matching at foo. We match character by character (unless we get to the beginning of baz). Then, we must match bar.

Going through your string, we start at foo. Good. We check if we're at the beginning of baz - we aren't. Grab a character (' '). Still not at the beginning of baz, so we grab another character (' a'). Still not at the beginning of baz, so we grab another character (' a '). Now we're at the beginning of baz, so we obviously went too far - back off (' a'), and exit the "loop". Next we need to match 'bar' - but 'bar' isn't here. Thus we failed to match anything. (Actually, we'll back off the two characters that we did match in the complex expression, but that will still fail to find 'bar'.)

One rule of thumb is to always check if a match succeeds before using any of the special variables. So try something like this:

if ( /foo # Match starting at foo (?: # Complex expression: (?!baz) # make sure we're not at the beginning of baz . # accept any character )* # any number of times bar # and ending at bar /x ) { # print stuff out. } else { print "Failed to match against '$_'\n"; }
Hope that helps,


In reply to Re: Regex look ahead by Tanktalus
in thread Regex look ahead by pglenski

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.