Regular Expressions in Perl
Perl's regex engine, explained with practical examples: matching, capture groups, substitution, and the modifiers and patterns you'll actually use.
- perl
- regex
- regular-expressions
- text-processing
Regular expressions are built into Perl at the language level, which is a big part of why Perl is so good at text. Here’s what you actually need.
Matching
The =~ operator binds a string to a pattern. // is the match:
my $text = "The order shipped on 2026-07-08";
if ($text =~ /shipped/) {
print "it shipped\n";
}
Capture groups
Parentheses capture parts of the match into $1, $2, …:
if ($text =~ /(\d{4})-(\d{2})-(\d{2})/) {
print "year=$1 month=$2 day=$3\n"; # year=2026 month=07 day=08
}
Substitution
s/// replaces matched text:
my $s = "colour and flavour";
$s =~ s/our/or/g; # "color and flavor" (g = replace all)
The modifiers you’ll use
g— global: match/replace every occurrence, not just the first.i— case-insensitive.m— multiline:^and$match at line breaks within the string.s— single line:.also matches newlines.x— extended: ignore whitespace in the pattern so you can space it out and comment it.
$text =~ /
(\d{4}) - (\d{2}) - (\d{2}) # an ISO date
/x;
The building blocks
| Pattern | Matches |
|---|---|
\d \w \s | digit, word char, whitespace |
\D \W \S | the negations |
. | any character (except newline) |
* + ? | zero-or-more, one-or-more, optional |
{2,5} | between 2 and 5 times |
^ $ | start / end of string (or line with /m) |
[abc] | any one of a, b, c |
(a|b) | a or b |
\b | a word boundary |
Extracting every match
In list context with /g, a match returns all captures — great for pulling structured data out of text:
my $log = "ip 10.0.0.1 ip 10.0.0.2 ip 10.0.0.9";
my @ips = $log =~ /ip (\S+)/g; # ("10.0.0.1", "10.0.0.2", "10.0.0.9")
A practical tip
Prefer specific patterns over greedy ones. .* is greedy and will grab as much as it can; use .*? (non-greedy) or a precise character class like [^"]* when parsing delimited text.
Where to go next
Put regexes to work at the command line in Perl One-Liners for Text Processing.