Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Perl shortcut to count the number of matches in a string?

Suppose I have:

my $string = "one.two.three.four"; 

How should I play with context to get the number of times the pattern found a match (3)? Can this be done using a one-liner?

I tried this:

my ($number) = scalar($string=~/\./gi); 

I thought that by putting parentheses around $number, I'd force array context, and by the use of scalar, I'd get the count. However, all I get is 1.

like image 541
Geo Avatar asked Dec 04 '09 20:12

Geo


People also ask

How do you count matches in a regular expression?

To count a regex pattern multiple times in a given string, use the method len(re. findall(pattern, string)) that returns the number of matching substrings or len([*re. finditer(pattern, text)]) that unpacks all matching substrings into a list and returns the length of it as well.

What is in Perl regex?

Regular Expression (Regex or Regexp or RE) in Perl is a special text string for describing a search pattern within a given text. Regex in Perl is linked to the host language and is not the same as in PHP, Python, etc. Sometimes it is termed as “Perl 5 Compatible Regular Expressions“.

How do I match in Perl?

m operator in Perl is used to match a pattern within the given text. The string passed to m operator can be enclosed within any character which will be used as a delimiter to regular expressions.


2 Answers

That puts the regex itself in scalar context, which isn't what you want. Instead, put the regex in list context (to get the number of matches) and put that into scalar context.

 my $number = () = $string =~ /\./gi; 
like image 61
friedo Avatar answered Sep 28 '22 05:09

friedo


I think the clearest way to describe this would be to avoid the instant-cast to scalar. First assign to an array, and then use that array in scalar context. That's basically what the = () = idiom will do, but without the (rarely used) idiom:

my $string = "one.two.three.four"; my @count = $string =~ /\./g; print scalar @count; 
like image 44
Robert P Avatar answered Sep 28 '22 04:09

Robert P