Regular Expressions, part 2

Part 1 gives a general overview of the meaning of operators.
Part 3 gives an overview of complex regular expressions.


A basic match

if ($string =~ /abc/){#code goes here}
The code is executed if the string contains abc anywhere in the varible $string
The opposite of this is:
if ($string !~ /abc/){#code goes here}
Test for abc at the begining

if ($string =~ /^abc/){#code goes here}
or end of a string
if ($string =~ /abc$/){#code goes here}
You can tell the match operator to ignore case with an i at the end:

if ($string =~ /abc/i){#code goes here}
matches ABC -- abc --AbC -- ABc and so on..
-or-
This uses the translate operator to make sure all letters are lower case:

$input =~ tr/A-Z/a-z/; 

Okay, lets see if you can figure out what this one does:

if ($count =~ /\n$/) {
   chop($count);
}

Here's an explanation. Chop removes the last character in a string, not just a line feed. This tests the string for a line feed before removing it. It is similar to chomp, which extracts all line feeds from a variable.


This regular expression leaves only numbers in $input

$input=~tr/0-9//cd;

And this is here because I use it all the time and can just come here and swipe it into my code:


if ($ENV{'HTTP_REFERER'} ne "" && $ENV{'HTTP_REFERER'} !~ /goldenink.com/){}


This is the standard code to clean out the trash that a web server throws into a URL if you are handling input from a "GET" action.


sub HtmlOut {

        # Decode the form encoding on the variables.          #
        $formfield =~ tr/+/ /;
        $formfield =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;

}

What it does:
The first line changes all '+' signs to blanks.
The second lines substitutes standard characters for the % representations.
Let's try one of the predefined escape sequences to split a string on the "whitespace";
   @words = split(/\s+/, $string);
Predefined sequences
\d Numeric [0-9]
\D Non-numeric [^0-9]
\w Alphameric [a-zA-Z0-9]
\W Non alphameric [^a-zA-Z0-9]
\s Whitespace [ \t\n\r\f]
\S Non whitespace [^ \t\n\r\f]

Part 3 gives an overview of complex regular expressions.

Return to Perl Help

[Our portfolio] [A history of Computers and Networks]
[Perl help] [ABAP help] [MySQL help]
[TCP/IP troubleshooting] [HTML help] [Feedback] [Humor]
Advertise on Golden Ink's Georgia Network


In Association with Amazon.com