Regex Matching
Regular expressions (regexes) are patterns that describe text. They are built right into Perl's syntax, which is a big reason Perl became the language of text processing. A pattern is written between slashes, and the binding operator =~ applies it to a string.
use strict;
use warnings;
my $sentence = "The quick brown fox jumps over the lazy dog";
if ($sentence =~ /fox/) {
print "Found a fox\n";
}
if ($sentence !~ /cat/) {
print "No cat here\n";
}
print "Has 'Quick'? ", ($sentence =~ /Quick/ ? "yes" : "no"), "\n";Found a fox
No cat here
Has 'Quick'? no
=~ returns true if the pattern matches anywhere in the string; !~ is its negation. Matching is case-sensitive unless you add the /i modifier (covered later).
Matching against $_
Without =~, a match tests the default variable $_. That makes filtering loops very short:
use strict;
use warnings;
my @log = (
"INFO server started",
"ERROR disk full",
"INFO user login",
"ERROR timeout",
);
for (@log) {
print "$_\n" if /ERROR/;
}
my $errors = grep { /ERROR/ } @log;
print "Total errors: $errors\n";ERROR disk full
ERROR timeout
Total errors: 2
Literal characters and metacharacters
Most characters match themselves. These metacharacters have special meanings and must be escaped with a backslash to match literally:
| Character | Meaning |
|---|---|
. |
any character except newline |
* + ? {n,m} |
quantifiers (repeat the previous item) |
^ $ |
start and end of the string |
[ ] |
character class |
( ) |
grouping and capturing |
| |
alternation ("or") |
\ |
escape |
use strict;
use warnings;
my @files = ("photo.jpg", "photojpg", "archive.tar.gz", "notes.txt");
for my $f (@files) {
my $any_char = $f =~ /o.j/ ? "yes" : "no";
my $real_dot = $f =~ /\.jpg/ ? "yes" : "no";
print "$f: o.j=$any_char \\.jpg=$real_dot\n";
}photo.jpg: o.j=yes \.jpg=yes
photojpg: o.j=no \.jpg=no
archive.tar.gz: o.j=no \.jpg=no
notes.txt: o.j=no \.jpg=no
/o.j/ needs an o, then exactly one character of any kind, then a j. In photo.jpg the dot fills that middle slot. In photojpg the j comes straight after the o, with nothing between them, so it fails. Escaping the dot (\.) makes it match only a real dot.
Alternation
| separates alternatives. Use parentheses to limit how far the alternation reaches:
use strict;
use warnings;
for my $pet (qw(cat dog parrot catfish hotdog)) {
my $whole = $pet =~ /^(cat|dog)$/ ? "exactly cat or dog" : "-";
my $part = $pet =~ /cat|dog/ ? "contains cat or dog" : "-";
printf "%-8s %-20s %s\n", $pet, $whole, $part;
}cat exactly cat or dog contains cat or dog
dog exactly cat or dog contains cat or dog
parrot - -
catfish - contains cat or dog
hotdog - contains cat or dog
^ and $ anchor the pattern to the start and end, so /^(cat|dog)$/ only matches the complete strings.
Variables in patterns
Patterns interpolate variables like double-quoted strings. When the variable holds user text that might contain metacharacters, wrap it in \Q...\E (or use quotemeta) so it is matched literally:
use strict;
use warnings;
my $price_text = "Total: 3.50 (incl. tax)";
my $search = "3.50 (incl";
print "Raw: ", (eval { $price_text =~ /$search/ } ? "match" : "error or no match"), "\n";
print "Quoted: ", ($price_text =~ /\Q$search\E/ ? "match" : "no match"), "\n";Raw: error or no match
Quoted: match
Without \Q, the ( in the search text starts an unclosed group, which is a regex syntax error (caught here by eval). With \Q, every special character is escaped.
Other delimiters
m followed by any delimiter also writes a match. This avoids "leaning toothpick syndrome" when the pattern contains slashes:
use strict;
use warnings;
my $url = "https://example.org/docs/index.html";
print "Docs URL\n" if $url =~ m{/docs/};
print "HTTPS\n" if $url =~ m!^https://!;Docs URL
HTTPS
Test yourself
What does $s =~ /ab/ test?
- Whether
$sequals "ab" - Whether "ab" occurs anywhere in
$s - Whether
$sstarts with "ab" - It assigns "ab" to
$s
How do you match a literal dot?
.\.[dot]$.
What is \Q$text\E for?
- Making the match case-insensitive
- Matching the contents of
$textliterally, escaping metacharacters - Quoting the output
- Ending the regex