Regular Expressions   «Prev  Next»
Lesson 2Introducing regular expressions
Objective Examine examples that use regular expressions

Using Regular Expressions

Regular expressions are a language used for parsing and manipulating text. They are often used to perform complex search-and-replace operations, and to validate that text data is well-formed. Today, regular expressions are included in most programming languages and scripting languages (like JavaScript). Furthermore regular expressions are incorporated into editors, applications, databases, and command-line tools. Pattern-matching operations of Perl enable the processing of log files and directories in any environment.
Regexps have been supported in Unix utilities for a very long time, and they are among the most powerful features of the Perl language. Using regular expressions, you can specify, select, search, and modify text and text-like data with power and ease.
For example, the expression /foo/ matches any line of text with the letters foo in it:
barefoot, buffoon, food, 
fool, football, footsteps, 

and under foot.
/categor(y|ies)/
will match categories, categor, and category's.

Of course, when you learn about the powerful features of regular expressions, you will find yourself writing regexps that are much more complex than these. For example, a simple program to validate yes/no input from a user might look like this without using a regex:

#!/usr/bin/perl

print "Do you want to play a game?\n";
$input=<STDIN>;
chomp($input)
if($input eq "yes" || $input eq "y")
  {print "Let's play!\n"}
else
  {print "Okay. Thanks anyway.\n"}

Using a regex you can shorten the if structure like this:
#!/usr/bin/perl

print "Do you want to play a game?\n";
$input=<STDIN>;
chomp($input)
if ($input=~/^y/i)
  {print "Let's play!\n"}
else
  {print "Okay. Thanks anyway.\n"}

The ^y tells the script to look for a word beginning with "y." The /i tells the script to ignore the case of the "y."
Admittedly, someone could answer yno or yesterday and this would still be treated as yes. As we learn more of the tools in regular expressions, we will revisit the yes/no program to make it more precise.
Mastering regular expressions will be an extremely useful skill for you. Perl uses a number of extensions to the common regular expressions that you may have used. In fact, Perl 5 has introduced some new extensions that are helpful in making regular expressions more readable.
The more you know about them, the better you will be able to solve common programming problems (and read other people's programs.) in Perl.