The Dopefly Tech Blog

<< The Dopefly Tech Blog Main page

Use the Java regular expression engine in ColdFusion

posted under category: ColdFusion on April 6, 2006 at 11:00 pm by MrNate

This is somewhat old news, but I've been using it lately, and figured I'd put a little reminder out here. Whenever you are trying to create a regular expression in ColdFusion and are having trouble with it, or if you're trying to use an advanced feature that just doesn't work (like lookbehind), remember that there IS a solution.

Here's a hint. Remember, CF is Java! Here's how to exploit the wonders of java.lang.String:

<cfset str = "This is my string!">
#str.matches("^.+$")#, displays YES
#str.replaceAll("\W","")#, displays Thisismystring
<cfdump var="#str.split("\W")#"/>, dumps an array of words

Everything you can do with a String can be found a the Java 1.4.2 API docs. (1.4.2 and not 1.5 because CFMX 6 & 7 support does not currently extend past 1.4.2)

Don't know enough about regular expressions? Learn more from the ColdFusion LiveDocs "Using Regular Expressions" pages, and also from regular-expressions.info.

Post A Comment!
On Apr 6, 2006 at 11:00 PM Trevor Burnette (trevor whose email lies with burnette.us) said:
Sweet. I never thought about using java.lang.String for my regex needs.

Here is a link to an article on using java to run regex against a file using java.

http://www.burnette.us/blog/index.cfm/2006/3/23/Using-Java-RegEx-in-ColdFusion-App

On Apr 6, 2006 at 11:00 PM John Allen (www.ogilvypr.com) said:
thanks for the reminder. good post.

On Apr 7, 2006 at 11:00 PM Michael White (mwhite007 from sbcglobal.net) said:
and just like magic, adobe has an article on how to upgrade your JRE to Sun's latest... found the article on MXNA:http://www.macromedia.com/cfusion/knowledgebase/index.cfm?id=2d547983&pss=rss_coldfusion_2d547983
and talking tree has a little more:http://www.talkingtree.com/blog/index.cfm/2006/4/7/CFAdmin-problems-when-editing-JVM-settings

On Jan 11, 2007 at 9:00 PM Ben Nadel (http://www.bennadel.com) said:
One note... you cannot call this on query records directly even if the query cell value is a string. The call:

Query.ColumnValue.ReplaceAll( .. )

Will throw an error because it doesn't know that the ColumnValue is a string. Underneath it must be some sort of "RecordCell" object or something.

To get around this, convert to a string first:

ToString( Query.ColumnValue ).ReplaceAll( .. )

That should be good to go!

On Jan 11, 2007 at 9:00 PM Nathan Strutz (http://www.dopefly.com/) said:
Ben,
To follow suit, you could also do this the slightly more java way...

query.columnValue.toString().replaceAll(...)

Just throwing that out there. It's not necessarily better in any way :)
Post A Comment!