Regular Expressions
This page is under construction. Please come back later.
#!/usr/bin/env perl use utf8; use English; use Utils; use strict; use warnings; MAIN: { binmode(STDOUT, ":utf8"); binmode(STDERR, ":utf8"); binmode(STDIN, ":utf8"); my $s = "Four score and seven years ago..."; print "Match 1: ", $s =~ qr/s.*e/, "\n"; print "Match 2: ", $s =~ qr/\bs.*e\b/, "\n"; print "Match 3: ", $s =~ qr/s...e/, "\n"; print "Match 4: ", $s =~ qr/b.d/, "\n"; my $subgroups = [$s =~ qr/((\w+)\s*(\w+))/]; print "Find First (with subgroups): ", Utils::listToString($subgroups), "\n"; $subgroups = [$s =~ qr/bad match/]; print "Find First (bad match): ", Utils::listToString($subgroups), "\n"; my $matches = [$s =~ m/\w+/g]; print "Find All: (matches only)", Utils::listToString($matches), "\n"; $matches = [$s =~ m/bad match/g]; print "Find All (bad match): ", Utils::listToString($matches), "\n"; }
Output
$ perl RegEx1.pl
Match 1: 1
Match 2: 1
Match 3: 1
Match 4:
Find First (with subgroups): [Four score, Four, score]
Find First (bad match): []
Find All: (matches only)[Four, score, and, seven, years, ago]
Find All (bad match): []
#!/usr/bin/env perl use utf8; use Utils; use strict; use warnings; MAIN: { binmode(STDOUT, ":utf8"); binmode(STDERR, ":utf8"); binmode(STDIN, ":utf8"); my $s = "Four score and seven years ago..."; print "Replace First 1: ", $s =~ s/\.\.\./!!!/r, "\n"; print "Replace First 2: ", $s =~ s/\b...\b/???/r, "\n"; print "Replace First 3: ", $s =~ s/b.d/???/r, "\n"; print "Replace First 4: ", $s =~ s/(\w+) (\w+)/$2 $1/r, "\n"; print "Replace All 1: ", $s =~ s/\b...\b/???/gr, "\n"; print "Replace All 2: ", $s =~ s/(\w+) (\w+)/$2 $1/gr, "\n"; }
Output
$ perl RegEx2.pl
Replace First 1: Four score and seven years ago!!!
Replace First 2: Four score ??? seven years ago...
Replace First 3: Four score and seven years ago...
Replace First 4: score Four and seven years ago...
Replace All 1: Four score ??? seven years ???...
Replace All 2: score Four seven and ago years...
#!/usr/bin/env perl use utf8; use Utils; use strict; use warnings; MAIN: { binmode(STDOUT, ":utf8"); binmode(STDERR, ":utf8"); binmode(STDIN, ":utf8"); my $str = "Four score and seven years ago..."; print "Split 1: ", Utils::listToString([split(qr/ /, $str)]), "\n"; print "Split 2: ", Utils::listToString([split(qr/[eo]/, $str)]), "\n"; print "Split 3: ", Utils::listToString([split(qr/\s/, $str)]), "\n"; print "Split 4: ", Utils::listToString([split(qr/\W/, $str)]), "\n"; }
Output
$ perl RegEx3.pl
Split 1: [Four, score, and, seven, years, ago...]
Split 2: [F, ur sc, r, and s, v, n y, ars ag, ...]
Split 3: [Four, score, and, seven, years, ago...]
Split 4: [Four, score, and, seven, years, ago]
Questions
- {{Who's on first?}}
- {{Who's on second?}}
- {{Who's on third?}}
Projects
More ★'s indicate higher difficulty level.
References
- [[Perl Language Reference]]
- [[Comprehensive Perl Archive Network (CPAN)]]
- [[Beginning Perl]], Simon Cozens
- [[Perl Monks Tutorials]]