When basic Perl regular expressions are not enough, we improve them using a number of different optional features.

Anchors are useful when we have specific requirements on the position of the pattern in the string. A caret (^) says that we want the pattern being at the beginning of the string, a dollar ($) is for the end.

If we want to check a string for having or not a full stop at its end, we could write this Perl code:

$pattern = "\.";
if(/$pattern$/) {
print "Full stop terminated string\n";

Notice that we have to quote the dot (.) because it is a metacharacter, meaning "whatever character but newline".

To check if our string begins with a specific pattern we write something like this:

$pattern = "It";
if(/^$pattern/) {
print "It starts the string\n";

Chapter 5 of Beginning Perl by Simon Cozens focuses on regular expressions.

No comments:

Post a Comment