Classes, Quantifiers and Anchors
A regex becomes powerful once you can say "any digit", "one or more" and "at the start". This lesson covers the three building blocks for that: character classes, quantifiers and anchors.
Character classes
Square brackets match one character from a set. A leading ^ inside the brackets negates the set, and - gives a range:
| Class | Matches |
|---|---|
[aeiou] |
one lowercase vowel |
[a-z0-9] |
a lowercase letter or digit |
[^0-9] |
any character that is not a digit |
[-.] |
a dash or a dot (a - first or last is literal) |
Common classes have shortcuts:
| Shortcut | Meaning | Negated |
|---|---|---|
\d |
digit [0-9] |
\D |
\w |
word character [A-Za-z0-9_] |
\W |
\s |
whitespace (space, tab, newline...) | \S |
. |
any character except newline |
use strict;
use warnings;
for my $code (qw(AB-1234 ab-1234 AB1234 XY-99z7)) {
my $ok = $code =~ /^[A-Z][A-Z]-\d\d\d\d$/ ? "valid" : "invalid";
print "$code: $ok\n";
}
my $text = "Room 42, floor 7";
my @digits = $text =~ /\d/g;
my @non_space = "a b\tc" =~ /\S/g;
print "Digits: @digits\n";
print "Non-space: @non_space\n";AB-1234: valid
ab-1234: invalid
AB1234: invalid
XY-99z7: invalid
Digits: 4 2 7
Non-space: a b c
The /g modifier with list assignment returns all matches; more on that in the modifiers lesson.
Quantifiers
A quantifier says how many times the previous item may repeat:
| Quantifier | Meaning |
|---|---|
* |
0 or more |
+ |
1 or more |
? |
0 or 1 (optional) |
{3} |
exactly 3 |
{2,4} |
2 to 4 |
{2,} |
2 or more |
use strict;
use warnings;
my @tests = ("color", "colour", "colouur", "123-4567", "12-34", "aaaah!", "ah");
for (@tests) {
my @hits;
push @hits, "colou?r" if /^colou?r$/;
push @hits, "phone" if /^\d{3}-\d{4}$/;
push @hits, "a{3,}h" if /a{3,}h/;
printf "%-9s %s\n", $_, (@hits ? "@hits" : "-");
}color colou?r
colour colou?r
colouur -
123-4567 phone
12-34 -
aaaah! a{3,}h
ah -
Greedy vs non-greedy
Quantifiers are greedy: they match as much as possible while still letting the whole pattern succeed. Add ? after a quantifier to make it lazy (as little as possible):
use strict;
use warnings;
my $html = '<b>bold</b> and <i>italic</i>';
my ($greedy) = $html =~ /(<.+>)/;
my ($lazy) = $html =~ /(<.+?>)/;
print "Greedy: $greedy\n";
print "Lazy: $lazy\n";
my @tags = $html =~ /<(\w+)>/g;
print "Opening tags: @tags\n";Greedy: <b>bold</b> and <i>italic</i>
Lazy: <b>
Opening tags: b i
The greedy .+ runs to the very last > in the string. The lazy .+? stops at the first >. Often an even better choice is a negated class, <[^>]+>, which simply cannot run past a >.
Anchors
Anchors match a position, not a character:
| Anchor | Position |
|---|---|
^ |
start of the string (or of a line with /m) |
$ |
end of the string, or just before a final newline |
\A, \z |
absolute start and end of the string |
\b |
word boundary (between \w and \W) |
\B |
not a word boundary |
use strict;
use warnings;
my $sentence = "cat concatenate scatter cat";
my $whole_words = () = $sentence =~ /\bcat\b/g;
my $anywhere = () = $sentence =~ /cat/g;
print "'cat' as a word: $whole_words, anywhere: $anywhere\n";
for my $line ("start here", " start late", "the end", "end of the story") {
my @tags;
push @tags, "begins with start" if $line =~ /^start/;
push @tags, "ends with end" if $line =~ /end$/;
print "'$line': ", (@tags ? join(", ", @tags) : "none"), "\n";
}'cat' as a word: 2, anywhere: 4
'start here': begins with start
' start late': none
'the end': ends with end
'end of the story': none
my $n = () = ... is a Perl idiom for counting matches: the match runs in list context (because of the empty list ()), and assigning that list assignment to a scalar gives the number of elements.
Tip: Always anchor validation patterns with
^...$(or\A...\z). Without anchors,/\d{4}/happily accepts"abc12345xyz".
Test yourself
Which pattern matches exactly three digits and nothing else?
/\d{3}//^\d{3}$//[0-9]+//\d*3/
What does [^aeiou] match?
- A vowel at the start
- One character that is not a lowercase vowel
- The string
^aeiou - Zero or more vowels
Applied to <a><b>, what does /<.+?>/ match?
<a><b><a><b>- nothing