Wednesday, October 27, 2010

My first regular expression!

I was working on a project yesterday that required some string validation. I had a vague sense of regular expressions, but never used them. I thought this might be a good chance to get my feet wet.

I needed to validate that a store name contained only letters, numbers, spaces or apostrophes. I didn't want any spaces before or after the store name and only single spaces between words in the name. I could probably get the job done with other string functions, but I knew regular expressions would be cleaner...a lot cleaner.

I did a little searching and came across this post, http://www.bennadel.com/blog/769-Learning-ColdFusion-8-REMatch-For-Regular-Expression-Matching.htm, by Ben Nadel and decided to give REMatch a try. I won't lie, it took me two hours to finally write the regular expression that did what I needed.

<cfset regexname = REMatch("(^( )[A-Za-z0-9]+)|([A-Za-z0-9]+(  ))|(  )|(( )$)|[^A-Za-z0-9 ']","#storename#")>


This function will return a variable, regexname, as an array. I check the array with ArrayIsEmpty(). If that function is true then the store name is valid. You see, the array would contain something if the REMatch function found an occurrence in  #storename# that matches one of the regular expressions. I actually wrote a group of regular expressions. There are 5 and they are separated by a pipe(|). The pipe character means OR. So what I end up with is a regular expression conditional statement.