Regular Expressions   «Prev  Next»
Lesson 10Using subexpressions
ObjectiveUse the s/// operator with subexpressions to perform selective text replacement.

Using Subexpressions with Perl

The substitution below will add commas to a long number. Europeans can use the same technique for adding periods.
while ($number =~ s/(.*\d)(\d\d\d)/$1,$2/g) { }
  1. The first subexpression (.*\d) will have all the characters except the last three digits, ensuring that at least four digits exist.
  2. The second subexpression (\d\d\d) has the last three digits. Since the /g modifier is not recursive, it is necessary to put this in a loop to make sure it gets all the numbers.

Substitution Expression

In order to step through the flow of this substitution expression, we are going to use the following SlideShow.

1) Regular Expression Digits 1 2) Regular Expression Digits 2 3) Regular Expression Digits 3 4) Regular Expression Digits 4

Program 1 Program 2 Program 2 Program 2
  1. Matches a minimum of 4 numbers in a row
  2. First iteration through the regular expression
  3. Second iteration through the regular expression
  4. Third iteration through the regular expression

Using Two Perl Subexpressions
Before you begin the exercise, you may want to explore more examples of selective replacement in action.

Edit File using Selective Replacement - Exercise

Click the Exercise link below to write a program that uses selective replacement on an email file.
Edit File using Selective Replacement - Exercise