Perl: Regex Tutorial
Check If String Match
To check if a string matches a pattern, do
str =~ m/regex_pattern/flags
captured pattern is in predefined variables
$1
, $2
, etc.
use utf8; # simple example of finding email address $text = 'this xyz@example.com that'; if ( $text =~ m/ (\w+\@\w+\.com) / ) { print "$1"; } else { print "no"; } # xyz@example.com
Find and Replace
To find and replace, do
str =~ m/regex_pattern/replace/flags
Any captured pattern is in predefined variables
$1
, $2
, etc
use utf8; $text = "123123"; $text =~ s/2/8/g; # g is a flag for global. meaning replace all occurrences print $text; # 183183
Here's a more complex example, replacing all “gif” image paths to “png” in HTML file.
$myText = qq[<p><img src="./rabbits.gif" width="30" height="20"> and <img class="xyz" src="../cats.gif">, but <img src ="tigers.gif">, <img src= "bird.gif">!</p>]; $myText =~ s/src\s*=\s*"([^"]+)\.gif"/src="\1.png"/g; # replacement on $myText print $myText; __END__ prints <p><img src="./rabbits.png" width="30" height="20"> and <img class="xyz" src="../cats.png">, but <img src="tigers.png">, <img src="bird.png">!</p>
Regex Quote Operator
you can create a regex string by qr
my $filenameRegex = qr{\.html$};
use utf8; my $text = 'this 2420 that'; my $regex = qr/(\d+)/; # Used as m// (matching) if ($text =~ $regex) { print "Matched $1\n"; } # Matched 2420 # Used as s// (substitution) $text =~ s/$regex/111/; print "$text\n"; # this 111 that
Regex Binding Operator
=~
is regex binding operator.
to be used with match operator m//
or substitution operator s//
example
$string =~ m/str/
$string =~ s/findStr/replace
Regex Match Operator
m//
is match operator
Regex Substitution Operator
s//
is substitution operator