Using Patterns for Search and Replace

One of the niftiest uses of regular expressions involves not just searching for a pattern or extracting matches into lists or variables or whatever, but also replacing that pattern with some other string. This is equivalent to a search and replace in your favorite word processor or editor—only with all the power and flexibility that regular expressions give you.

To search for a pattern and then replace it with some other pattern, use this syntax:

s/pattern/replacement/

For this syntax the pattern is some form of regular expression; replacement is the string that will replace the match. A missing replacement will delete the match from the string. For example:

s/s+/ /   # replace one or more whitespace characters with a single space

As with regular patterns, this syntax will search and replace the string in $_ by default. Use the =~ operator to search a different location.

The search-and-replace syntax, as shown, will replace only the first match, and return 1. With the /g option (g stands for global) on the end, Perl will replace all instances of the pattern in the string with the replacement:

s/--/—/g # replace two dashes -- with an em dash code —

Also, as with regular patterns, you can use the /i option at the end to perform a search that's not case sensitive (although the replacement will not match case, so be careful):

s/a/b/gi;  # replace [Aa] with b, globally

Feel free to use parentheses and match variables inside search-and-replace patterns; they work just fine here:

s/^(S+)/=$1=/g  # put = signs around first word
s//^(S+)(s.*)(S+)$/$3†$2†$1/ # swap first and last words

Note

Fans of sed will think that it's better to use 1, 2, and so on in the replacement part of the search and replace. Although this will work in Perl (basically by Perl replacing those references with variables for you), you should really get out of the habit—officially, in Perl, the replacement part of the s/// expression is a plain old double-quoted string, and 1 means a different thing in that context.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset