Previous Table of Contents Next


If you've started to figure out the pattern to regular expressions, try this quiz to see what you've learned.



If you have lines formatted "x=y", what expression would swap the left and right sides of the expression?

  1. s/(.+)=(.+)/$2=$1/;

  2. s/(*)=(*)/$2=$1/;

  3. s/(.*)=(.*)/$2$1/;


After this code, what's the value in $2?

$foo="Star Wars: The Phantom Menace";

$foo=~/star\s((Wars): The Phantom Menace)/;

  1. $2 is not set after the pattern match because the match fails.

  2. Wars

  3. Wars: The Phantom Menace


What does the pattern m/^[-+]?[0-9]+(\.[0-9]*)?$/ match?

  1. Dates in the format 04-03-1969

  2. Well-formed numbers such as 45, 15.3, -0.61

  3. Addition-looking patterns: 4+12 or 89+2



a. Choice c doesn't include the = symbol in the replacement string and it wasn't captured in $1 or $2 because the = occurred outside of the parentheses. Choice b is invalid; a character must appear in front of the *'s. Choice a does the job nicely.


a. The match fails because star is not capitalized, and the match doesn't have the noncase-sensitive modifier i. For this reason, you should always test whether the match succeeds before using the values $1, $2, and so on. (If the pattern match had used the i modifier or star had been capitalized, choice b would have been the correct response.)


b. The pattern reads, at the beginning of the line match, an optional + or -, followed by one or more digits, followed (optionally) by a decimal and possibly more digits at the end of the line. The pattern matches simple, well-formed numbers.


  • See whether you can produce a pattern to match a standard time format. All the following should be acceptable: 12:00am, 5:00pm, 8:30AM. These should probably not be accepted: 3:00, 2:60am, 99:00am, 3:0pm.

  • Write a short program that does the following:

    1. Opens a file

    2. Reads all the lines into an array

    3. Extracts all the words from each line

    4. Finds all words that have at least four consecutive consonants, or nonvowels (such as the words "thoughts" or "yardstick")

    Previous Table of Contents Next
    © 2000- NIV