[Buffalo-pm] regexp returning count of pattern.

Kevin Eye eye at buffalo.edu
Tue Jan 17 09:30:41 PST 2006


The /g flag on regex substitutions returns the number of substitutions.

Try this:

$text = 'abcba';
$num_substitutions = $text =~ /b/d/g;

$num_substitutions is 2 because two b's were replaced with d's.

You can do this without substitutions to count the number of matches, too.

 - Kevin


On 1/17/06 12:26 PM, "Josh Johnson" <joshj at linuxmail.org> 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?
> 
> -Josh J

-- 
Kevin Eye
Web Applications Developer
Marketing and Creative Services
University at Buffalo
330 Crofts Hall
Buffalo, NY 14260
eye at buffalo.edu
phone (716) 645-5000 x1435
fax (716) 645-3765




More information about the Buffalo-pm mailing list