Skip navigation.
Your source for Perl tips, howto's, faq and tutorials

print lines matching a pattern exactly 'n' times

( categories: | )

The key is to do the match with the 'g' modifier in list context, then compare the result in scalar context to obtain the number of matches.


Print the lines in 'file.txt' that have the string 'for' repeated exactly 3 times:

perl -ne 'print if ( ( () = /for/g ) == 3 )' file.txt

match the shortest possible string

( categories: )

The pattern matching quantifiers of a Perl regular expression are "greedy" (they match the longest possible string). To force the match to be "ungreedy", append a ? to the pattern quantifier (*, +).


#-- greedy match
$string =~ /^(.*)s/;
print "$1\n"; # prints 111s11111
#-- ungreedy match
$string =~ /^(.*?)s/;
print "$1\n"; # prints 111

Syndicate content