Think of it this way:  \w{2,}? matches the minimum possible of two or more 'somethings', in this case  \w characters. On its first try it matches two characters (and prints them). The match is then intentionally 'failed', so  \w{2,}? gets another chance to match beginning at the point at which it previously attempted the match (not at that point + 1), this time matching three characters. And so on through four, five, ... Only when the regex engine runs out of  \w thingies to match is it forced to move the initial match point forward and try some more, starting again with two characters.

Contrast with the behavior of  "ABCDEF" =~ /(\w{2,})(?{print "$1\n"})(?!)/; (no  ? quantifier modifier: greedy matching).

In the original  "ABCDEF" =~ /([A-Z]{3})(?{print "$1\n"})(?!)/; case,  [A-Z]{3} can only match exactly three characters, so the regex engine must advance the trial match point upon failure; no backtracking (or forward-tracking, if that's even a correct term, in the case of lazy matching) is possible: exactly three characters and some other stuff were required to match at a given point; the match failed; move on — nothing to see here, folks.

Update: Sorry: many small additions, wording changes, etc., which should not have altered essential meaning.


In reply to Re: regex backtracking question by AnomalousMonk
in thread regex backtracking question by aeqr

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.