in reply to positions of all regexp matches

my $string = "hello world ballloon"; my $regex = qr/ll/; my @matches; push @matches, [$-[1], $+[1]] while $string =~ /(?=($regex))/g; print "@$_\n" for @matches;
Note the care given to find overlapping matches.

-- Randal L. Schwartz, Perl hacker
Be sure to read my standard disclaimer if this is a reply.

Replies are listed 'Best First'.
Re: •Re: positions of all regexp matches
by flounder99 (Friar) on Oct 14, 2003 at 18:58 UTC
    Look, ma, no loops!
    use re 'eval'; my $string = "hello world ballloon"; my $regex = qr/ll/; my @matches; () = $string =~ /(?=$regex)(?{push @matches, pos})./g; print join "\n", @matches; __END__ 2 14 15

    --

    flounder

        You are right about the not finding the \n since I didn't add an s at the end of the m//. But if you don't have the . in there it will find the positions twice.
        use re 'eval'; my $string = "he\nllo world ba\nllloon"; my $regex = qr/\nll/; my @matches; () = $string =~ /(?=$regex)(?{push @matches, pos})./sg; print "with .\n", join "\n", @matches; @matches = (); () = $string =~ /(?=$regex)(?{push @matches, pos})/sg; print "\n\nwithout .\n", join "\n", @matches; __END__ with . 2 15 without . 2 2 15 15

        --

        flounder