[Edinburgh-pm] Regex not matching what I expect (or want:)

Aaron Crane perl at aaroncrane.co.uk
Sat Jul 31 11:32:06 PDT 2010


Miles Gould <miles at assyrian.org.uk> wrote:
> to get all overlapping matches
>
> $n = "8907455758584";
> @ns = $n =~ /(?=(\d{3}))/g;
> say "@ns";

An alternative approach:

  my $n = "8907455758584";
  my @ns;
  while ($n =~ /\G(\d{3})/g) {
      push @ns, $1;
      pos($n) = $-[0] + 1;
  }
  say "@ns";

The crucial bit is the assignment to pos($n); see `perldoc -f pos` for
what that does.

This is more complicated (and probably slower) for this specific task,
but I think there are overlapping-match situations where the lookahead
technique wouldn't work, and a variant of this approach would — you
can make the next match attempt to start at any arbitrary position in
the string, even choosing it based on what match you found.

-- 
Aaron Crane ** http://aaroncrane.co.uk/


More information about the Edinburgh-pm mailing list