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("This is a test", "\W", "_", 
           "All")>
  • Replace all spaces in a filename with the underscore character; this is useful in situations where you allow users to upload files to your ColdFusion server via their web browsers:

    <cfset NewFilename = REReplace("My File Name.txt", " ", "_", "All")>
  • Return the full directory path from a string containing a full path including filename:

    <cfset TheDirectory = REReplaceNoCase(MyPath, "\w+\.\w+", "", "All")>
  • Return the filename from a string containing a full path including filename:

    <cfset TheFileName = REReplaceNoCase(MyPath, "([A-Z]:\\)|\w+\\+", "", "All")>
  • Remove all doubled words in a string:

    <cfset NoRepeats = REReplaceNoCase("I want to to go to the park.", 
      "\b([a-z]+)[ ]+\1","\1","All")>
  • Strip all HTML tags from a string; this is useful for removing HTML from form-field submissions:

    <cfset NoHTML = REReplace(MyString, "<[^>]*>", "", "All")>
  • Remove all HTML anchors in a string, leaving just the text, if any:

    <cfset NoHTMLLinks = 
      REReplaceNoCase(MyString, "<a [^>]*>([[:print:]]*)</a>","\1",'All')>
  • Format all email addresses in a string as HTML mailto: links. Note ...

Get Programming ColdFusion MX, 2nd Edition 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.