Perl logo


Perl Refreshments ⌘

Regular Expressions #2 - Match Operators

To begin talking about regexes, we can start with something simple, like the match operator: m//.

As it sounds, it is used to see if your object string matches a particular string.

It is used like this:

my $text = "There is an anchor somewhere in here.";
if ($text =~ m/anchor/) {
     print "Found an anchor!\n";
}

Note the binding operator =~, which binds a scalar expression to a pattern match.

=~ binds a scalar expression to a pattern match

!~ negate the return value (does NOT match)

my $text = "There is an anchor somewhere in here.";
if ($text !~ m/mermaid/) {
     print "No mermaids in here.\n";
}

Match beginning or end of a string

Two common metacharacters are the ^ and $ to match the beginning and end of a string.

For example, you are asking the user to enter some data, then type 'quit' when they are done. One way to do this is as follows:

while (<>) {
     if (m/quit/) {exit;}
}

This is translated by the regex engine to mean match a "q", followed by a "u", followed by an "i", followed by a "t".

Sounds about right, but what if the user types "Don't quit"?

The code would find the word "quit" in the string and exit, as it should. Not what we want.

A better regex might be:

while (<>) {
     if (m/^quit$/i) {exit;}
}

This translates to match a "q" at the beginning of the string, followed by a "u", followed by an "i", followed by a "t" at the end of the string.

And in case the user types "QUIT","Quit","quIt", etc., we use the i modifier to indicate a case insensitive match.

Regex 3 - Pattern Modifiers & Back References ...
-30-