For "xxxx", "x*" matches the null width "beginning" then matches all the "x"s to the end.

Well, that would mean the first result would be 1, not 2. What happens is that /x*/ matches the zero-length string at the beginning, all the x-es, but not the zero-length string at the end. After the first substitution, the regex hasn't reached the end of the string yet, so /g kicks in. All that's left is the zero-width string at the end - this is now matched (were it wasn't before), and hence we get a second substitution, resulting in a result of 2 and a final "##" string.

Frankly, I find this behaviour unexpected and unwanted. I'd call it a bug, but I bet someone once had a use for this, and now that's the way it goes.

Abigail


In reply to Re: Regex (counting) confusion :( by Abigail-II
in thread Regex (counting) confusion :( by snax

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.