Look-ahead is (?= ), not (?: ) !

13:46 >perl -wMstrict -MData::Dump -E "my $foo = '123456789'; my @w1 = + ($foo =~ /(?=(\d{3}))/g); dd \@w1;" [123, 234, 345, 456, 567, 678, 789] 13:46 >

Update: The use of (?: ) instead of (?= ) appears to be a misprint in the Camel Book.

The following explanation from that same section (page 248) is worth noting (at least, it helped me to understand what is going on):

When the engine sees that it should try again because of the /g, it steps one character past where last it tried.

This explains why the final . in BrowserUk’s solution is not strictly necessary. But BrowserUk’s regex can be usefully generalised to step forward an arbitrary number of characters. For example, to capture 3 digits and then step forward 2 characters:

17:56 >perl -wMstrict -MData::Dump -E "my $foo = '123456789012345'; my + @w1 = ($foo =~ /(?=(\d{3})).{2}/g); dd \@w1;" [123, 345, 567, 789, 901, 123, 345] 18:09 >

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,


In reply to Re: Lookahead assertion by Athanasius
in thread Lookahead assertion by talexb

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.