2009.01.07...8:29 pm

Regular Expression String to replace “&=”

Jump to Comments

So I have an issue where I need to move some CF8 code to a CF7 server. Unfortunately my code is littered with one of my favorite operators “&=” for string concatenation and this construct is not valid in CF7. In order to make my code work I need to convert all of my “&=” operators into var = var & string type statements.

Since I use FlexBuilder/Eclipse for my development I am able to take advantage of the advanced Find/Replace feature that uses regular expressions.

Here is the regular expression that I came up with to do my replacements.

Find: (^\s+)(.+)(\x26=)
Replace With: $1$2 = $2 \&

Here is a breakdown of what each part of each of these does

The Find string:

( starts capture group #1
^ matches the start of a line
\s matches white space
+ says to match ‘many’ of the previous char (white space)
) ends capture group #1

( starts capture group #2
. matches any character
+ says to match ‘many’ of the previous char (any character)
) ends capture group #2

( starts capture group #3
\x26 matches a char with hex code of 26 (ampersand)
= matches an equal sign
) ends capture group #3

The Replace string:

$1 Inserts capture group 1
$2 Inserts capture group 2
= Inserts and equal sign
$2 Inserts capture group 2
\& Inserts an ampersand (the \ is for escaping)

So the way this works is

Given the following line of code
stringVar &= ’some more text’;

  • Capture group 1 (^\s+) matches the start of the new line and the indentation.
  • Capture group 2 (.+) then matches to the var name “stringVar”
  • Capture group 3 (\x26=) then matches to the operator “&=”
  • Replace then inserts capture group 1 (the new line and indentation)
  • then it inserts capture group 2 (the var name “stringVar”)
  • then it inserts and equal sign “=”
  • then it inserts capture group 2 again (the var name “stringVar”)
  • finally it inserts an ampersand “&”

The final string becomes
stringVar = stringVar & ’some more text’;

Note that the expression only actually operates on the part of the line in blue and does not alter the rest of the line of code.

Leave a Reply