Loading...

Count the number of matches of a particular character in a string matched by a regex wildcard

Answer #1 100 %

You would have to capture the string matched and process it separately.

This code demonstrates

use strict;
use warnings;

my $str = '> plantagenetgoosewagonattributes';

if ($str =~ />(.*)[^a]+/) {
  my $substr = $1;
  my %counts;
  $counts{$_}++ for $substr =~ /./g;
  print "'$_' - $counts{$_}\n" for sort keys %counts;
}

output

' ' - 1
'a' - 4
'b' - 1
'e' - 4
'g' - 3
'i' - 1
'l' - 1
'n' - 3
'o' - 3
'p' - 1
'r' - 1
's' - 1
't' - 5
'u' - 1
'w' - 1
Answer #2 85.7 %

Outside of the regex :

my $p_count = map /p/g, />(.*)[^a]/;

Self-contained:

local our $p_count;
/
   (?{ 0 })
   >
   (?: p (?{ $^R + 1 })
   |   [^p]
   )*
   [^a]
   (?{ $p_count = $^R; })
/x;

In both cases, you can easily expand this to count all letters. For example,

my %counts;
if (my ($seq = />(.*)[^a]/) {
   ++$counts{$_} for split //, $seq;
}

my $p_count = $counts{'p'};

You’ll also like:


© 2023 CodeForDev.com -