Regular Expressions Gotcha
I was playing with some code the other day and ran into a 'gotcha' that I should have seen. I knew it in a different situation and just didn't apply it to what I was doing at the time.
Basically, ColdFusion can store a Regular Expression in a variable and then use that variable within a REFind/REReplace function as if the expression was written there. In other words, ColdFusion evaluates the variable, sees that it is in the Regular Expression position of the function and uses it as the expression to parse.
If this is so well known, then what was the problem? I was doing a search for a piece of text and then use a REReplace function to replace the text I found with a different piece of text. Straightforward and all but the text that I found had a parenthesis in it (an open and a close to be exact). This means that it was a valid Regular Expression and was to be parsed. All I wanted to do was use it as the replace text, but ColdFusion wanted to do something else with it.
Bottom line is that after beating my head against the wall looking at the data I ran a few tests and then a few more and saw the issue. Makes me feel really foolish when I can't apply a known gotcha to an unknown problem. :(
Here's the code to showcase the issue:
<cfset Searchtext="trim(name)">
<cfset Position=REFind(Searchtext, String)>
<cfset String=REReplace(String, Searchtext, '<b>\1</b>')>
<cfoutput>#Position#-#String#</cfoutput>
Because this was a REReplace and the text was coming from a search, I didn't see the text, didn't realize that it was a valid Regular Expression and didn't realize that it would fail (Variable stored Regular Expressions are almost always used in REFind examples). It's times like this that I could use a really good debugger to see what's happening in each variable as it changes. Luckily, that debugger should be out in a few weeks.

