You must take care that your lookbehind, if incorporated into the same regexp, doesn't change what you match. If it's too greedy, the starting point of the former pattern might shift backwards.

So, IMO, the safest way is to use two patterns. I'm not sure if you can integrate it into one pattern, I doubt it, so that you can still simply make the whole match fail if the lookbehind fails. Two independent matches won't do that. Anyway, enough blahblah, here's my coarse idea:

my $success; while(/PATTERN/g) { if(substr($_, 0, $-[0]) =~ /LOOKBEHIND\z/) { # got a match! $success = 1; last; } }
For example:
$_ = 'bar bar obar foooooobar bar'; my($success, $start) = 0; while(/bar/g) { if(substr($_, 0, $start = $-[0]) =~ /fo+\z/) { # got a match! $success = 1; last; } } print "$success: $start\n";
printing:
  1: 35
Using $start, the start position of the outer match, you can try again if you want, to get the captured values and @- and @+. For some odd reason, capturing @- and @+ in the loop made it loop forever. *shrug*

In reply to Re: Substitute for variable-length look-behind? by bart
in thread Substitute for variable-length look-behind? by diotalevi

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.