Now let's take a look at replacing characters in a string using regular expressions. The replace functions that we have access to are REReplace() and REReplaceNoCase(). Just as with find functions, the difference between these two is simply that one is case-sensitive whereas the other is not. REReplace() is case-sensitive. These two functions also share the same syntax requirements with three required parameters:
REReplace(string, reg_expression, substring [, scope ]) REReplaceNocase(string, reg_expression, substring [, scope ])
The first required parameter is the string that you want to parse. You can hardcode this string (that is, enclose it in double quotes), or you can call a variable:
<cfset newstvar=REReplace("this is the stuff that I want to parse", "stuff", "string", "One")> <cfoutput> newstvar = #newstvar# </cfoutput>
<cfset stvar="this is the stuff that I want to parse"> <cfset newstvar=REReplace(stvar, "stuff", "string", "One")> <cfoutput> newstvar = #newstvar# </cfoutput>
The second required parameter is the expression that you want to replace. We can see in the last example that this could be a string, but it could also be a pattern that we want to match. Look at the following example:
<cfset URL="http://www.insidecoldfusion.org"> <cfoutput> URL = #url# <br><br> #ReplaceNoCase(URL, 'http://', '')# </cfoutput>
Your resulting output would look like Figure 10.2.
Figure 10.2. Sample regular expression output.
Let's revisit our examples from earlier in the chapter:
<cfset secretmessage = REReplace("E!V!A!C!U!A!T!E! !N!O!W!", "[[:punct:]]", "", "ALL")>
<cfset secretmessage = REReplace(REReplace("I243*w22i3423ll*m2e678e21t234*y234121ou231*083l3452a2343te34r", "[[:digit:]]", "", "ALL"), "[[:punct:]]", " ", "ALL")>
Of course, this is not an example that you'll likely use, but it illustrates a point about REReplace() and REReplaceNoCase(). Now let's take a look as some examples of how you might use regular expressions in your ColdFusion applications: