Examples

Example 1-1. Simple match

# Find Spider-Man, Spiderman, SPIDER-MAN, etc.
my $dailybugle = "Spider-Man Menaces City!";
if ($dailybugle =~ m/spider[- ]?man/i) { do_something(  ); }

Example 1-2. Match, capture group, and qr

# Match dates formatted like MM/DD/YYYY, MM-DD-YY,...
my $date  = "12/30/1969";
my $regex = qr!^(\d\d)[-/](\d\d)[-/](\d\d(?:\d\d)?)$!;
if ($date =~ $regex) {
  print "Day=  ", $1,
        " Month=", $2,
        " Year= ", $3;
}

Example 1-3. Simple substitution

# Convert <br> to <br /> for XHTML compliance
my $text = "Hello World! <br>";
$text =~ s#<br>#<br />#ig;

Example 1-4. Harder substitution

# urlify - turn URLs into HTML links
$text = "Check the web site, http://www.oreilly.com/catalog/
regexppr.";
$text =~
     s{
      \b                         # start at word boundary
      (                          # capture to $1
       (https?|telnet|gopher|file|wais|ftp) :
                                 # resource and colon
       [\w/#~:.?+=&%@!\-] +?     # one or more valid
                                 # characters
                                 # but take as little as
                                 # possible
      )
      (?=                        # lookahead
           [.:?\-] *             #  for possible punctuation
        (?: [^\w/#~:.?+=&%@!\-]  #  invalid character
          | $ )                  #  or end of string
      )
     }{<a href="$1">$1</a>}igox;

Get Regular Expression Pocket Reference, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.