Finding dates in a string using ColdFusion

A reader of mine had an interesting question. Is it possible to find all the dates in a string? In theory you could parse all the words and attempt to turn each into a date. You would need to check each word and a “reasonable” amount of words after it. Perhaps up to 4. I decided to take an initial stab at a simpler solution - looking just for dates in the form of mm/dd/yyyy. (Note to all of my readers outside of America. The code I’m showing here would actually work fine in your locales as well.)

First - let's create a simple string.

<cfsavecontent variable="str"> This is some text. I plan on taking over the world on 12/1/2011. After I do that, I plan on establishing the Beer Empire on 1/2/2012. But on 3/3/2013 I'll take a break. But this 13/91/20 is not a valid date. </cfsavecontent>

Now let's do a regex based on Number/Number/Number.

<cfset possibilities = reMatch("\d+/\d+/\d+", str)>

This gives us an array of possible matches that we can loop over:

<cfloop index="w" array="#possibilities#"> <cfif isDate(w)> <cfoutput>#w# is a date.<br/></cfoutput> </cfif> </cfloop>

Which gives us...

12/1/2011 is a date.
1/2/2012 is a date.
3/3/2013 is a date.

Any thoughts on this technique? The entire template is below.

<cfsavecontent variable="str"> This is some text. I plan on taking over the world on 12/1/2011. After I do that, I plan on establishing the Beer Empire on 1/2/2012. But on 3/3/2013 I'll take a break. But this 13/91/20 is not a valid date. </cfsavecontent> <cfset possibilities = reMatch("\d+/\d+/\d+", str)> <cfloop index="w" array="#possibilities#"> <cfif isDate(w)> <cfoutput>#w# is a date.<br/></cfoutput> </cfif> </cfloop>

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA https://www.raymondcamden.com

Comments