An Introduction to Regular Expressions The Substitution Operator 32 of 50 : [PREV] [NEXT]

Usage

The REPLACEMENT can also consist of backreferences. The classic substitution example is one that swaps the first two words of a string:

s/(\S+)\s+(\S+)/$2 $1/

The first two words, each matched by the sub-pattern \S+, are surrounded by parentheses that enable backreferences. So $1 reflects the first word in the string, and $2 reflects the second one. In this case, it makes no sense to use the /g modifier, because we are interested in swapping once the first two words.


© 2003 Barbie barbie@missbarbell.co.uk Home http://birmingham.pm.org/