Useful Regular Expressions
Now that you have a better idea of how regular expressions work, let’s take a look at how you can actually use them in your own ColdFusion applications. Here are some regular expressions that perform common search-and-replace tasks:
Replace all characters in a string that aren’t numbers, letters, or underscores with an underscore:
<CFSET NewString = REReplaceNoCase(MyString, "[^0-9A-Z_]", "_", "All")>
Replace all spaces in a filename with the underscore character; useful in situations where you allow users to upload files to your ColdFusion server via their web browsers:
<CFSET NewFilename = REReplace(MyFileName, "( )", "_", "ALL")>
Return the full directory name from a string containing a full path including filename:
<CFSET TheDirectory = REReplaceNoCase(MyPath, "[A-Z0-9_]+\.[A-Z0-9_]+", "All")>
Return the filename from a string containing a full path including filename:
<CFSET TheFileName = REReplaceNoCase(MyPath, "([A-Z]:\\)|[A-Z0-9_]+\\+", "", "All")>
Remove all doubled words in a string:
<CFSET NoRepeates = REReplaceNoCase(MyString, "([A-Z]+)[ ]+\1","\1","All")>
Strip all HTML tags from a string; useful for removing HTML from form-field submissions:
<CFSET NoHTML = REReplace(MyString, "<[^>]*>", "", "All")>
Remove all HTML from links in a string, leaving just the URL:
<CFSET NoHTMLLinks = REReplaceNoCase(MyString, "<a *href[^>]+>([^(</a>)]*)</a>","\1",'All')>
Format all email addresses in a string as HTML mailto links:
<CFSET MailtoLinks = REReplace(MyString, ...
Get Programming ColdFusion now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.