Suppose for a moment that you have a variable that you want to ensure it only contains numeric data. For instance a telephone, PIN, or credit card number.
ColdFusion makes this extremely simple to using a regular expression with the reReplace and reReplaceNoCase functions, as I will demonstrate below. For those new to ColdFusion the “re” in reReplace and reReplaceNoCase stands for “regular expression.”
<cfset variables.myDirtyPhoneNbr = '(555) 222-4444'> <cfset variables.myCleanPhoneNbr = reReplaceNoCase(variables.myDirtyPhoneNbr, '[^[:digit:]]', '', 'ALL') > <!--- Now let's display the cleaned phone number ---> <cfoutput>#variables.myCleanPhoneNbr#</cfoutput> <!--- myCleanPhoneNbr should now be: 5552224444 --->
With a few exceptions, ColdFusion supports Perl compliant Regular Expressions. For more information, check out the online documents at: http://livedocs.adobe.com/coldfusion/8/htmldocs/help.html?content=regexp_13.html
2013.03.01 – One of our readers pointed out a mistake in the code example, a “:” was missing between “[digit” and the closing “]”. Thanks for catching that.