Pulling A Substring Out Of A String With Regular Expressions And ColdFusion 8

September 17, 2009

Development

cf_appicon

I have a love/hate relationship with . (Okay, so it’s more hate than love) But one of the aspects of the programming language that I have come to love is it’s simplicity with dealing with regular expressions. Using predefined methods such as reFind() and reReplace() have made task, which could have been overly frustrating, very streamlined. If there was one thing that I would have said it was lacking it would be the ability to take a substring out of a string based upon a matched regular expression.

For example, what if I only wanted to not only check a string for the presence of an IP address but also pull it directly from the string into it’s own variable?

For example, given the following string:

“The IP Address is 192.168.0.1. Booyah!”

It would require some multi-step string manipulation, which is neither fun nor productive, to pull out the value “192.168.0.1″ and place it into it’s own variable.

But thanks to Coldfusion 8 and the method this can now be done very easily. All we need is a well formed regular expression and a string.


<!---

reMatch() Example

--->

<cfset variables.search_string = "The IP Address is 192.168.0.1. Booyah!" />

<cfset variables.regex_ip_address = "(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:[.](?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}" />

<cfset variables.ip_address = reMatch(variables.feeds_regex_ip_address, variables.search_string) />

<cfdump var="#variables.ip_address#" label="IP Address Match" />

The output from the following bit looks like this:

rematch_output

Super Easy! But it’s not even the best part. The best part is that the reMatch() method returns an array of matched strings, not just a single value. So if we had multiple matches, given the string:

“The IP address is 192.168.0.1. Booyah! Or was is 255.255.255.255?”

The output would then become:

rematch_output_multi

Could this be any nicer? Maybe some predefined “built in” regular expressions to go along with it? Maybe in CF 9.

, ,

No comments yet.

Leave a Reply