[Buffalo-pm] regexp returning count of pattern.

John Macdonald john at perlwolf.com
Tue Jan 17 10:03:58 PST 2006


On Tue, Jan 17, 2006 at 12:26:42PM -0500, Josh Johnson wrote:
> I need a way to get the count of a pattern being matched. I can make up an elaborate function to do this but I wondered if perl had something built in I could use. For example, say I have the string:
> 
> $string = 'abcdeeeeeefgheeeeijk';
> 
> I'd like to replace it with something like:
> 
> 'abcdE=6fghE=4ijk'
> 
> Is there any way I can get a regexp to return the number of times that a parameter was matched?

(warning: untested)

    $string =~ s/(([a-z])\1+)/"\U$1=".length($2)/ge;

matches a lowercase letter as the first part <<([a-z])>>,
repeated at least one more time <<\1+>>.  The replacement is
eval'ed to uppercase the character <<"\U$1=" and compute the
number of total matches <<length($2)>>.  The e flag causes
the eval, and the g flag repeats the substitution as often as
possible in the original string.


--


More information about the Buffalo-pm mailing list