> I think I've understood now 👍

maybe this helps, you can reproduce it in the debugger started with perl -de0

DB<22> p $_ = join "," , A..E A,B,C,D,E DB<23> p m/(,.*,)/ # longest possibility from first comma to last c +omma ,B,C,D, DB<24> p m/(,.*?,)/ # shortest possibility from first comma to next +comma ,B, DB<25> p m/(,.*$)/ # longest possibility from first comma to end of + line ,B,C,D,E DB<26> p m/(,.*?$)/ # shortest possibility from first comma to end o +f line ,B,C,D,E DB<27>

the regex-engine tries to find a solution step by step:

The problem with your regex was, that it was already matching from the leftmost comma.

But all solutions provided by other monks made sure that only the rightmost comma allowed to be a match.

For instance

DB<27> p m/(,[^,]*)$/ # comma followed by non-commas till EOL ,E

The engine will actually try to first match all other commas to the left but always fail because it encounters other commas before reaching the EOL.

we can actually make the regex display it's intermediate attempts to match while "backtracking"

DB<32> ; m/(,[^,]*) (?{say $1}) $/x #show all intermediate attempts +to match $1 until it doesn't fail ,B , ,C , ,D , ,E DB<33>

The difference with non-greedy quantifier *? matching is that the engine goes from shortest to longest attempts while backtracking

DB<34> ; m/(,[^,]*?) (?{say $1}) $/x #show all intermediate attempts + to match $1 , ,B , ,C , ,D , ,E DB<35>

Is this clearer now? :)

HTH!

Cheers Rolf
(addicted to the Perl Programming Language :)
see Wikisyntax for the Monastery


In reply to Re^3: Non-greedy substitution by LanX
in thread Non-greedy substitution by Bod

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.