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,
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.