Regular expressions: match and anchors
Match with =~
A pattern sits between slashes, and the binding operator =~ applies it to the string on the left. The expression returns true or false, so it fits directly in an if.
Without a left side the pattern tests $_, which is how one-liners and short loops stay short.
my $line = "error: disk full";
print "matched\n" if $line =~ /error/;
print "clean\n" if $line !~ /error/;
perl demo.pl
matched
Anchors
A pattern matches anywhere in the string unless you anchor it. The caret anchors to the start, the dollar sign to the end, and \b to a word boundary.
my $line = "error: disk full";
print "starts\n" if $line =~ /^error/;
print "ends\n" if $line =~ /full$/;
print "word\n" if $line =~ /\bdisk\b/;
perl demo.pl
starts
ends
word
The dollar sign matches before a trailing newline too, which is what you want when matching lines read from a file. For a strict end of string use \z.
Character classes
Square brackets list the characters that may appear in one position; a dash makes a range. The backslash shortcuts cover the common sets, and their uppercase forms negate them.
my $code = "AB-123";
print "letters\n" if $code =~ /[A-Z]{2}/;
print "digits\n" if $code =~ /\d+/;
print "nospace\n" if $code =~ /^\S+$/;
perl demo.pl
letters
digits
nospace
The shortcuts are \d for digits, \w for word characters, \s for whitespace, and . for any character except a newline. Capitalize one to invert it.
Quantifiers
Quantifiers say how many times the previous piece may repeat. The star allows zero or more, the plus one or more, and the question mark zero or one. Braces give an exact range.
my $ver = "v5.40.1";
print "semver-ish\n" if $ver =~ /^v\d+\.\d+\.\d+$/;
print "at least two\n" if $ver =~ /\d{2,}/;
perl demo.pl
semver-ish
at least two
Quantifiers are greedy by default: they take as much as possible, then give characters back until the rest of the pattern matches. Add a question mark after one to make it lazy, which matters for HTML-like text.
Flags
Letters after the closing slash change how the whole pattern behaves. The three you need first are i for case-insensitive, x for readable patterns with spaces and comments, and g for repeated matching.
my $text = "ERROR: DISK FULL";
print "noisy\n" if $text =~ /error/i;
my $re = qr{ ^ \w+ # first word
: \s \w+ # colon, space, second word
$ }x;
print "words\n" if $text =~ $re;
perl demo.pl
noisy
The x flag ignores whitespace and lets comments in, so a complicated pattern can be laid out like code. Start using it the first time a pattern does not fit in one comfortable line.
The x flag changes only the layout of the pattern, not what it matches: $re is still anchored with $, so it wants a line with exactly two words. This text has three, which is why the second print stays silent.
Next: Captures and named groups
Article author: Arthur Isaev