Using Sub-Expressions with Replacement Variables

The replace function allows parenthesized sub-expressions (also known as groups) to be referenced by number in the replacement string. In the $replacement string, you can use the variables $1, $2, $3, etc. to represent (in order) the parenthesized expressions in $pattern. This is very useful when replacing strings on the condition that they come directly before or after another string—for example, if you want to change instances of the word Chap to the word Sec, but only those that are followed by a space and a digit. This technique can also be used to reformat data for presentation. Table 18-16 shows some examples.

Table 18-16. Examples of using replacement variables

Example

Return value

replace("Chap 2...Chap 3...Chap 4...","Chap (d)", "Sec $1.0")

Sec 2.0...Sec 3.0...Sec 4.0...

replace("abc123", "([a–z])", "$1x")

axbxcx123

replace("2315551212", "(d{3})(d{3})(d{4})", "($1) $2-$3")

(231) 555-1212

replace("2006-10-18", "d{2}(d{2})-(d{2})-(d{2})", "$2/$3/$1")

10/18/06

replace("25", "(d+)", "$$1.00")

$25.00

The variables are bound in order from left to right based on the position of the opening parenthesis. The variable $0 can be used to represent the string matched by the entire regular expression. If the variable number exceeds the number of parenthesized sub-expressions in the regular expression, it is replaced with a zero-length string.

If you wish to include the character $ in your replacement string, you must escape it with a backslash (i.e., $), as shown in the fifth example. Backslashes must also be escaped in the $replacement string, as in \.

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

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