[ ^ CSE 341 | section index | <-- previous | next -->]

Regular expressions

Regular expressions come in two basic flavors: match and substitute. They are denoted by a preceding m and s respectively; the m is optional if you use slashes:

my $str = "Perl is a language for getting stuff done."; my $str2 = $str . "\nThis is an example of Perl."; $str =~ /Perl/; # Equivalent to m/Perl/ $str =~ m%(st.*e)\.%; # Equivalent to m/(st.*e)\./ print $1 . "\n"; $str =~ s/stuff/a lot of stuff/; $str2 =~ s/[Pp]erl/Python/mg; $str =~ s/^(.*) is a language (.*).$/$2, you can turn to $1./; print "$str\n", "$str2\n";

Try deciphering the following on your own. Will each expression match? What will be saved (if anything) in the saved match variables $1, $2, etc.?

my $foo = "Peter piper picked a peck of pickle peppers."; my $bar = "How much wood could a woodchuck chuck?\n"; my $bif = "The sixth sheik's\nsixth sheep\nwas sick\n"; $foo =~ m/(p.*ck)/; print "$1\n"; $foo =~ /(p.*?ck)/ and print "$1\n"; print ($foo =~ m/[Pp][oua]/); $bar =~ s/o[ou].*?d/eep/g and print $bar; $bif =~ s/six/seven/ and print $bif; $bar =~ /(.ep)/; $bif =~ s/^(.*) (.*)$1/$2ark the $1/m; print $bif;

Last modified: Wed Apr 12 18:57:15 PDT 2000