Perl: Regular Expression (regex) Example

, , …,

Check If String Match

To check if a string matches a pattern, do str =~ m/regex pattern/flags. Any captured pattern will be in predefined variable {$1, $2, …}

#-*- coding: utf-8 -*-
# perl

# simple example of finding email address

$text = 'this xyz@example.com that';

if ( $text =~ m/ (\w+\@\w+\.com) / ) {
    print "$1";                 # xyz@example.com
} else {
    print "no";
}

Find & Replace

To find & replace, do str =~ m/regex pattern/replace/flags. Any captured pattern will be in predefined variable {$1, $2, …}

Here's a simple example of using regex to replace text.

#-*- coding: utf-8 -*-
# perl

$text = "123123";
$text =~ s/2/8/g; # g is a flag for global. meaning replace all occurances
print $text; # 183183

Here's a more complex example, replacing all “gif” image paths to “png” in HTML file.

# -*- coding: utf-8 -*-
# perl

$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>
blog comments powered by Disqus