Perl: Regex Tutorial

By Xah Lee. Date: . Last updated: .

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 and Replace

To find and 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 occurrences
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>

If you have a question, put $5 at patreon and message me.

Perl

  1. Perl Overview
  2. Version String
  3. Help System

Detail

  1. Quoting String
  2. Format String
  3. String Operations
  4. True, False
  5. if then else
  6. Loop
  7. List / Array
  8. Loop Thru List
  9. Map f to List
  10. List Comprehension
  11. Hash Table
  12. Function Optional Param
  13. regex

Text Processing

  1. Unicode 🐪
  2. Convert File Encoding
  3. Read Write File
  4. Traverse Dir
  5. Find Replace
  6. Validate Local Links
  7. Split Line by Regex

Advanced

  1. Sort List, Matrix, Object
  2. Sort Matrix
  3. Sort Unstable
  4. Sort Misc
  5. List Modules, Search Paths
  6. Write a Module
  7. Complex Numbers
  8. System Call
  9. gzip
  10. Get Env Var
  11. GET Web Content
  12. Email