Perl Quick Lab 51 character classes, g option, + quantifier, - | and b meta characters, pattern memory () and $1

Copyright ã1998, 1999 Alonzo L. Hosford, Jr.

Best viewed in IE or Netscape 4.0 or higher version

 

Required: Notepad, MSDOS Prompt, Windows version of Perl, hard drive or floppy disk to save files.

 

1.       Windows: Create a work folder on your hard drive or use a floppy disk as your work folder.

2.       Windows: Start Windows Note Pad

3.       Notepad: Type the following text.

#!/usr/bin/perl

# regexp17.pl

# regular expressions

# the substitution operator

# meta character \b

# pattern memory

print "Regular expressions\n";

print "Substitution operator s// \n";

print "Use of the g option (global) \n";

print "Use of quantifier + \n";

print "Use of meta character b (word boundary) \n";

print "Use of meta character | (or) \n";

print "Use of character class and range meta character \n";

print "Use of pattern memory variables. In this case \$1 \n";

 

print "Substitutes all cases of one or more contiguous numbers \n";

print "enclosed in word boundary or one or more contiguous numbers a comma\n";

print "followed by one or more contiguous numbers all enclosed in a word boundary.\n";

print "The match is surrounded by parenthesis.\n\n";

 

$myline = "About 18 brown baby foxes ran after the 35,499 rabbits at the BBB ranch.";

$_ = $myline;

 

print "\$_ before  = $_\n";

 

 

$result = s/\b([0-9]+,[0-9]+|[0-9]+)\b/\($1\)/g;

 

print "\$_ after            = $_\n";

print "expression          = \\b([0-9]+,[0-9]+|[0-9]+)\\b\n";

print "replacingText       = (\$1)\n";

print "\$result             = $result\n";

print "substitutions       = $result\n";

4.       Notepad: Save in your work folder as regexp18.pl.

5.       Windows task bar: Select MSDOS Command Prompt.


6.       MSDOS Command Prompt: Test the syntax. Type the following and press the Enter key:

perl regexp18.pl                                                

Example of output:

A:>

perl regexp18.pl

Regular expressions

Substitution operator s//

Use of the g option (global)

Use of quantifier +

Use of meta character b (word boundary)

Use of meta character | (or)

Use of character class and range meta character

Use of pattern memory variables. In this case $1

Substitutes all cases of one or more contiguous numbers

enclosed in word boundary or one or more contiguous numbers a comma

followed by one or more contiguous numbers all enclosed in a word boundary.

The match is surrounded by parenthesis.

 

$_ before  = About 18 brown baby foxes ran after the 35,499 rabbits at the BBB r

anch.

$_ after            = About (18) brown baby foxes ran after the (35,499) rabbits

 at the BBB ranch.

expression          = \b([0-9]+,[0-9]+|[0-9]+)\b

replacingText       = ($1)

$result             = 2

substitutions       = 2