Welcome to www.mmclean.ca!
2 Nov 2026
Summary
This article provides some useful Regular Expressions that may be used in Perl scripts. Prior knowledge of Perl and Regular Expressions is assumed.

Regular Expressions

One of the key features of Perl I have found is the powerful Regular Expression engine. Text searching and manipulation is greatly simplified once you understand some of the basics of Regular Expressions. For example, string searches may be performed for a match based on a general pattern or text may be extracted from between two patterns. The following a few Regular Expressions I have employed in the past:

# IP Address validation.
$ip =~ m/^( \d | [01]?\d\d | 2[0-4]\d | 25[0-5] )\.
                  ( \d | [01]?\d\d | 2[0-4]\d | 25[0-5] )\.
                  ( \d | [01]?\d\d | 2[0-4]\d | 25[0-5] )\.
                  ( \d | [01]?\d\d | 2[0-4]\d | 25[0-5] )$/x ;

# Remove leading and trailing spaces.
$line =~ s/^\s+//;
$line =~ s/\s+$//;

# Remove CRLF from line.
$line =~ s/[\x0A\x0D]//;

# Remove all double-quotes from string. Useful if parsing a CSV.
$entry =~ s/\"//g;

# Extract substring after pattern found. Pattern must be at beginning of string.
# $line = Accept-Language: en-us             => from HTTP Header.
if( $line =~ m/^Accept\-Language:\s(.*)/ )
{
  my $language = $1; # en-us
}

# Format string so that first letter of each word is capitalized and rest of 
# characters are lower-case.
$delim = ' ';
$format_str =~ s/($delim|^)(.*?)(?=$delim|$)/$1\u\L$2/sg;

# Extract string between two tokens. Doesn't matter if there is CRLF between 
# tokens.
if( $data =~ /$start_token(.*)$end_token/s )
{
  my $parsed_result = $1;
}

# Format Canadian postal code. If postal code contains a dash, replace it 
# with a space.
$postal_code =~ s/\-/$delim/ ;

# Match if quit or exit found. Case-insensitive.
$entry =~ m/(quit|exit)/i ;