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 nth 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.




Banner.Novgorod.Ru