Languages: Python C C++ Go Java Ruby Rust Perl R ← Full TOC

← Perl Index

🔍 Regex — Regular expressions — Perl's superpower

Perl invented the modern regex syntax that every other language copied. Full support for named captures, lookaheads, lookbehinds, modifiers, and inline code.

📋 Functions & Syntax

NameSignatureDescription
=~$str =~ /PATTERN/flagsMatch string against regex
!~$str !~ /PATTERN/True if string does NOT match
m//m/PATTERN/flags → boolExplicit match operator
s///s/PATTERN/REPLACEMENT/flags → countSubstitution operator
tr///tr/FROM/TO/ → countTransliterate characters
g flag/pattern/gGlobal: match all occurrences
i flag/pattern/iCase-insensitive matching
m flag/pattern/m^ and $ match at line boundaries
s flag/pattern/s. matches newline too
x flag/pattern/xExtended: allow whitespace and comments
$1..$9capture group variables$1 = first capture, $2 = second, etc.
$+{name}named capture: (?<name>...)Named capture group result
(?:...)non-capturing groupGroup without capturing
(?=...)positive lookaheadMatch if followed by pattern
(?!...)negative lookaheadMatch if NOT followed by pattern
(?<=...)positive lookbehindMatch if preceded by pattern
(?<!...)negative lookbehindMatch if NOT preceded by pattern
\w \d \scharacter classesWord char / digit / whitespace
\W \D \Snegated classesNon-word / non-digit / non-whitespace
\b \Bword boundary assertionsWord boundary / non-boundary
+ * ? {n,m}quantifiersOne-or-more / zero-or-more / optional / range
+? *? ??non-greedy quantifiersMinimal matching versions
@matchesmy @m = ($str =~ /pat/g)Collect all matches into array
qr//qr/PATTERN/flags → RegexpCompile regex into reusable object

💡 Example

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

← Core Perl  |  🏠 Index  |  File IO →