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

Miles Gould miles at assyrian.org.uk
Sat Jul 31 11:19:18 PDT 2010


On Sat, Jul 31, 2010 at 05:21:43PM +0100, Iain Barnett wrote:
> $n = "8907455758584";
> @ns = $n =~ /\d{3}/g;
> print "@ns";

Some Googling turns up this page:

http://linuxshellaccount.blogspot.com/2008/09/finding-overlapping-matches-using-perls.html

which says that you need to use lookahead assertions (which don't
swallow characters that they match) to get all overlapping matches. This
code does what you want.

#! /usr/bin/perl

use 5.010;

$n = "8907455758584";
@ns = $n =~ /(?=(\d{3}))/g;
say "@ns";

HTH,
Miles

-- 
Lispers are among the best grads of the Sweep-It-Under-Someone-Else's-Carpet
School of Simulated Simplicity.
  -- Larry Wall


More information about the Edinburgh-pm mailing list