Perl invented the modern regex syntax that every other language copied. Full support for named captures, lookaheads, lookbehinds, modifiers, and inline code.
| Name | Signature | Description |
|---|---|---|
| =~ | $str =~ /PATTERN/flags | Match string against regex |
| !~ | $str !~ /PATTERN/ | True if string does NOT match |
| m// | m/PATTERN/flags → bool | Explicit match operator |
| s/// | s/PATTERN/REPLACEMENT/flags → count | Substitution operator |
| tr/// | tr/FROM/TO/ → count | Transliterate characters |
| g flag | /pattern/g | Global: match all occurrences |
| i flag | /pattern/i | Case-insensitive matching |
| m flag | /pattern/m | ^ and $ match at line boundaries |
| s flag | /pattern/s | . matches newline too |
| x flag | /pattern/x | Extended: allow whitespace and comments |
| $1..$9 | capture group variables | $1 = first capture, $2 = second, etc. |
| $+{name} | named capture: (?<name>...) | Named capture group result |
| (?:...) | non-capturing group | Group without capturing |
| (?=...) | positive lookahead | Match if followed by pattern |
| (?!...) | negative lookahead | Match if NOT followed by pattern |
| (?<=...) | positive lookbehind | Match if preceded by pattern |
| (?<!...) | negative lookbehind | Match if NOT preceded by pattern |
| \w \d \s | character classes | Word char / digit / whitespace |
| \W \D \S | negated classes | Non-word / non-digit / non-whitespace |
| \b \B | word boundary assertions | Word boundary / non-boundary |
| + * ? {n,m} | quantifiers | One-or-more / zero-or-more / optional / range |
| +? *? ?? | non-greedy quantifiers | Minimal matching versions |
| @matches | my @m = ($str =~ /pat/g) | Collect all matches into array |
| qr// | qr/PATTERN/flags → Regexp | Compile regex into reusable object |
Run with perl script.pl.
#!/usr/bin/perl
use strict;
use warnings;
use feature 'say';
# Basic matching
my $email = 'user@mywebuniversity.com';
if ($email =~ /\A([\w.+-]+)@([\w-]+\.[\w.]+)\z/) {
say "Valid email: $email";
say " User: $1";
say " Domain: $2";
}
# Named captures
my $date = '2026-06-25';
if ($date =~ /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/) {
say "Year=$+{year} Month=$+{month} Day=$+{day}";
}
# Global match — collect all occurrences
my $text = 'The price is $42.99 and $19.50 and $7.00';
my @prices = ($text =~ /\$(\d+\.\d{2})/g);
say "Prices: @prices";
my $total; $total += $_ for @prices;
printf "Total: \$%.2f\n", $total;
# Substitution
(my $clean = $text) =~ s/\$\d+\.\d{2}/PRICE/g;
say "Cleaned: $clean";
# Multi-line log parsing
my $log = <<'END';
2026-06-01 10:23:45 ERROR 503 /api/users 152ms
2026-06-01 10:24:01 INFO 200 /api/posts 43ms
2026-06-02 09:10:00 WARN 429 /api/users 0ms
END
while ($log =~ /^(\S+)\s+(\S+)\s+(ERROR):\s+(.+)$/mg) {
printf " [%s] %s\n", $1, $4 if defined $4;
}
while ($log =~ /^(\S+)\s+\S+\s+(\w+)\s+(\d+)\s+(\S+)\s+(\d+)ms$/mg) {
printf " %s %s %s %s %sms\n", $1,$2,$3,$4,$5;
}
# perl regex_demo.pl