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.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does $line =~ /error/ do?

    Answer

    It applies the pattern to $line and returns true or false

    =~ is the binding operator, and a match returns a boolean that fits directly in a condition; !~ negates it.

  2. What does $ match at the end of a pattern?

    Answer

    The end of the string, or a position before a trailing newline

    That is what line matching needs; \z is the strict end of the string when a newline must not be allowed.

  3. What does capitalising a shortcut, as in \D or \W, do?

    Answer

    It inverts the set, so \D matches anything that is not a digit

    Each shortcut has an uppercase form that matches the complement of the lowercase one.

  4. What do *, + and ? mean after a piece of a pattern?

    Answer

    Zero or more, one or more, zero or one

    The star is the loosest of the three, and braces give an exact range when a count is needed.

  5. What does greedy matching mean?

    Answer

    The quantifier takes as much as possible, then gives characters back until the rest matches

    A star or plus runs to the end and backtracks; a question mark after the quantifier makes it lazy.

  6. Which flag lets a complicated pattern use spaces and comments?

    Answer

    x

    The x flag ignores whitespace in the pattern and makes # start a comment, so the pattern can be laid out like code.

  7. What does this program print? my $s = "error: disk full"; print "starts\n" if $s =~ /^error/;

    Answer

    starts

    The caret anchors the pattern to the start of the string, where error sits.

  8. What does this program print? my $code = "AB-123"; print "digits\n" if $code =~ /\d+/;

    Answer

    digits

    \d+ finds the run of digits anywhere in the string and the match is true.

  9. What does this program print? my $ver = "5.40.1"; print "semver\n" if $ver =~ /^\d+\.\d+\.\d+$/;

    Answer

    semver

    Each \. matches a literal dot and each \d+ one or more digits, so the whole string is three numbers.

  10. What does this program print? my $line = "done\n"; print "end\n" if $line =~ /done$/;

    Answer

    end

    $ also matches just before a trailing newline, which is why it works on lines read from a file.

Article author: Arthur Isaev