Quantifiers

Learn how to use regex with quantifiers in Perl.

We'll cover the following...

Matching literal expressions is good, but regex quantifiers make regexes more powerful. These metacharacters govern how often a regex component may appear in a matching string. The simplest quantifier is the zero or one quantifier, or ?:

Perl
use Test::More;
my $cat_or_ct = qr/ca?t/;
like 'cat', $cat_or_ct, "'cat' matches /ca?t/";
like 'ct', $cat_or_ct, "'ct' matches /ca?t/";
done_testing();

Any atom in a regular expression followed by the ? character means “match zero or one instance(s) of this atom.” This regular expression matches if zero or one a characters immediately follow a c character and immediately precede a t character. This regex matches the literal substrings cat and ct ...