As tomte suggests, you can achieve this using deferred evaluation; the trick is to take advantage of the special variable $^N, which refers to "the most recently closed capture" in the match so far.

Using this, we get for example:

% perl -le 'print $& if shift =~ /(\d)(((??{$^N + 1})))+/' 4321234 1234 %

This works because the first time through the eval we have seen (for example) the digit '1', so we return '2' as the next thing to match; if we match it, that match is itself captured and becomes the last thing captured, so the next time into the eval $^N is '2' and we return '3' as the new thing to match.

Note firstly that $^N was introduced in perl-5.8.0, so you won't be able to use this with earlier versions; secondly, enabling warnings gives the unexpected complaint:

(((??{$^N + 1})))+ matches null string many times before HERE mark in +regex m/((\d)(((??{$^N + 1})))+ << HERE )/ at -e line 1.
.. which looks like a bug, and you can safely ignore that warning in this case.

Hugo


In reply to Re: regexp for searching incremental expressions by hv
in thread regexp for searching incremental expressions by mod_alex

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.