Search⌘ K
AI Features

Quantifiers

Explore how to use quantifiers in Perl regular expressions to control how often patterns match. Understand the zero or one, one or more, zero or more, and numeric quantifiers to write clear and efficient regex for text processing.

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 ...