![]() ![]() ![]() |
ColdFusion Server supports backreferencing, which allows you to match text in previously matched sets of parentheses. A slash followed by a digit n (\n) is used to refer to the nth parenthesized sub-expression.
One example of how backreferencing can be used is searching for doubled words -- for example, to find instances of `the the' or `is is' in text. The following example shows the syntax you use 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 sub-expression 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
You can now use backreferences in replace strings. Backreferences in the replace string refer to parenthesized matched sub-expressions in the regular expression search. For example, to replace all repeated words in a text string with a single word, you can 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, ReturnSubExpression, 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"
To use backreferences in either the search string or the replace string, you must use parentheses around the sub-expression. Otherwise, ColdFusion throws an exception.
![]() ![]() ![]() |
AllaireDoc@allaire.com
Copyright © 1998, Allaire Corporation. All rights reserved.