Jeri has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

If I have a string "LLL" and I want to capture a count of how many times "LL" occurs, I would expect the count to be 2, but in the way my regular expression is written I'm getting a count of only 1. Do I have to use seek to get the appropriate count? Here's what I've written. How can I get it to recognize the last two LLs as a pair?

my @matches = ($_=~m/.*("LL").*/g); if(@matches){foreach(@matches){$counter++;}}

Replies are listed 'Best First'.
Re: Regex catching multiple characters next to each other
by roboticus (Chancellor) on Oct 06, 2014 at 06:05 UTC
Re: Regex catching multiple characters next to each other
by blindluke (Hermit) on Oct 06, 2014 at 06:05 UTC

    If you're interested in the count, try this approach:

    #!/usr/bin/perl use v5.14; $_ = 'LLL'; my @matches = m/(L)(?=L)/g; say scalar @matches; #prints 2, as expected

    The (L)(?=L) expression looks for every 'L' immediately followed by another 'L'. As there are two such matches, the @matches array contains two elements.

    regards,
    Luke Jefferson

      use v5.14;

      NB: Perl version 5.14 is needed only for say. The regexery works fine under 5.8.9 (tested) and I think it would work as well under 5.0, but I can't test back that far and I'm too lazy to check the docs.

        It sure works on 5.8.8 that ships with my AIX. Still, I have at least two other reasons for using the 'use 5.14;' line: it's a good shortcut for 'use strict;', and it's an expression of my firm belief that we should try to promote using modern versions of Perl as often as possible.

        But you are right in making it clear that if someone wants to use this approach, he should not be discouraged by the version statement I used. I should have added this to my reply. Thank you.

        Luke Jefferson

Re: Regex catching multiple characters next to each other
by Laurent_R (Canon) on Oct 06, 2014 at 06:11 UTC
Re: Regex catching multiple characters next to each other
by AnomalousMonk (Archbishop) on Oct 06, 2014 at 12:54 UTC
    And if you're just interested in the number of overlaps, here's a way based on an approach covered in the recent node already linked (with the actual overlaps thrown in as a convincer):
    c:\@Work\Perl\monks>perl -wMstrict -le "my $s = '1234'; ;; my $n =()= $s =~ m{ (?= (\d\d)) }xmsg; print qq{total overlaps: $n}; ;; my @overlaps = $s =~ m{ (?= (\d\d)) }xmsg; printf 'overlaps:'; printf qq{ '$_'} for @overlaps; " total overlaps: 3 overlaps: '12' '23' '34'