Perl Regex: Tutorial

Regex is regular expression and forms an integral part of Perl.

Perl Regular expressions make it easy to do some of the following:

a. Complex string comparisons
b. Complex string selections
c. Complex string replacements
d. Parsing based on the above abilities

We will go in detail in the examples below. But, before that we define how regex works: metacharacters and repetition:

Perl Regex Metacharacters

char meaning
^ beginning of string
$ end of string
. any character except newline
* match 0 or more times
+ match 1 or more times
? match 0 or 1 times; or: shortest match
| alternative
( ) grouping; “storing”
[ ] set of characters
{ } repetition modifier
\ quote or special

Perl Regex Repetition: Examples

a* zero or more a’s
a+ one or more a’s
a? zero or one a’s (i.e., optional a)
a{m} exactly m a’s
a{m,} at least m a’s
a{m,n} at least m but at most n a’s repetition? same as repetition but the shortest match is taken

Perl Regex Examples

s/foo/bar/;
replaces the first occurrence of the exact character sequence foo in the “current string” (in special variable $_) by the character sequence bar; for example, foolish bigfoot would become barlish bigfoot

s/foo/bar/g;
replaces any occurrence of the exact character sequence foo in the “current string” by the character sequence bar; for example, foolish bigfoot would become barlish bigbart

s/foo/bar/gi;
replaces any occurrence of foo case-insensitively in the “current string” by the character sequence bar (e.g. Foo and FOO get replaced by bar too)

if(m/foo/)…
tests whether the current string contains the string foo

Finding Files in Perl Using Regular Expression


#!/usr/local/bin/perl
#
# search for a file in all subdirectories
#
if ($#ARGV != 0) {
print "usage: findfile filename\n";
exit;
}

$filename = $ARGV[0];

# look in current directory
$dir = `pwd`;
chop($dir);
&searchDirectory($dir);

sub searchDirectory {
local($dir);
local(@lines);
local($line);
local($file);
local($subdir);

$dir = $_[0];

# check for permission
if(-x $dir) {

# search this directory
@lines = `cd $dir; ls -l | grep $filename`;
foreach $line (@lines) {
$line =~ /\s+(\S+)$/;
$file = $1;
print “Found $file in $dir\n”;
}

# search any sub directories
@lines = `cd $dir; ls -l`;
foreach $line (@lines) {
if($line =~ /^d/) {
$line =~ /\s+(\S+)$/;
$subdir = $dir.”/”.$1;
&searchDirectory($subdir);
}
}
}
}

Comments on this entry are closed.

css.php