Using Backreferences
265
Using Backreferences
ColdFusion Server supports
backreferencing
, which allows you to match text in
previously matched sets of parentheses. A slash followed by a digit n (\n) refers to the
n
th
subexpression in parentheses.
One use for backreferencing is in searching for doubled words; for example, to find
instances of “the the” or “is is” in text. The following example shows the syntax for
backreferencing in regular expressions in ColdFusion:
REReplace("There is is coffee in the the kitchen",
"([A-Za-z]+)[ ]+\1","*","ALL")
This code searches for words that are all letters ([A-Za-z]+) followed by one or more
spaces [ ]+ followed by the first matched subexpression in parentheses. The parser
detects the two occurrences of is as well as the two occurrences of the and replaces
them with an asterisk, resulting in the following text:
There * coffee in * kitchen
Using backreferences in replacement strings
You can use backreferences in replacement strings. Backreferences in the
replacement string refer to matched subexpressions in the regular expression search.
For example, to replace all repeated words in a text string with a single word, use the
following syntax:
REReplace("There is is a cat in in the kitchen",
"([A-Za-z]+)[ ]+\1","\1")
This results in the sentence:
“There is a cat in in the kitchen”
You can use the optional fourth parameter in
REReplace
, scope, to replace all
repeated words, as in the following code:
REReplace("There is is a cat in in the kitchen",
"([A-Za-z]+)[ ]+\1","\1","ALL")
This results in the following string:
“There is a cat in the kitchen”
Note
To use backreferences in either the search string or the replace string, you must use
parentheses around the subexpression. Otherwise, ColdFusion throws an exception.
Summary of Contents for COLDFUSION 5-DEVELOPING
Page 1: ...Macromedia Incorporated Developing ColdFusion Applications MacroMedia ColdFusion 5 ...
Page 58: ...38 Chapter 3 Querying a Database ...
Page 134: ...114 Chapter 7 Updating Your Database ...
Page 210: ...190 Chapter 10 Reusing Code ...
Page 232: ...212 Chapter 11 Preventing and Handling Errors ...
Page 238: ...218 Chapter 12 Using the Application Framework ...
Page 262: ...242 Chapter 12 Using the Application Framework ...
Page 278: ...258 Chapter 13 Extending ColdFusion Pages with CFML Scripting ...
Page 320: ...300 Chapter 15 Indexing and Searching Data ...
Page 336: ...316 Chapter 16 Sending and Receiving E mail ...
Page 374: ...354 Chapter 18 Interacting with Remote Servers ...