Perl Regular Expressions

Pattern matching with regular expressions

Basic Matching

if ($string =~ /pattern/) { # match operator
    print "Match found\n";
}
if ($string !~ /pattern/) { # negative match
    print "No match\n";
}

Substitution

$string =~ s/old/new/; # replace first occurrence
$string =~ s/old/new/g; # replace all occurrences
$string =~ s/old/new/i; # case-insensitive

Capture Groups

if ($string =~ /(\w+)@(\w+)/) { # capture groups
    print "User: $1\n"; # first capture
    print "Domain: $2\n"; # second capture
}

Character Classes

/\d/ # digit [0-9]
/\w/ # word character [a-zA-Z0-9_]
/\s/ # whitespace
/\D/ # non-digit
/\W/ # non-word character
/\S/ # non-whitespace

Quantifiers

/a*/ # zero or more
/a+/ # one or more
/a?/ # zero or one
/a{3}/ # exactly 3
/a{2,5}/ # 2 to 5

Anchors

/^start/ # start of string
/end$/ # end of string
/\bword\b/ # word boundary