A colleague of mind asked me this afternoon if I knew of a way, in ColdFusion, and one of line of code, to determine if all of the elements in a short list are contained in a larger list. He also wanted to discount the order of the elements in the larger list – the elements could be anywhere. I quickly indexed my mental store of ColdFusion list functions, and nothing came to mind, so my first answer was no. Then I thought about it for a minute and realized that he could use my trusted friend and companion – regular expressions.
I figured if there was a way to convert the list itself into a regular expression pattern using lookaheads, then it would be a snap. I then went to LiveDocs and discovered the ListChangeDelims() function which I had never used before. It was perfect.
<cfset largeList = "127.0.0.1,192.168.0.1,63.25.178.45,12.87.65.102,155.189.37.121">
<cfset smallList = "192.168.0.1,12.87.65.102">
<cfset allElementsInLargeList = ReFind( "^(?=.*#ListChangeDelims(smallList,')(?=.*', ',')#).*$", largeList)>
<cfdump var="#allElementsInLargeList#">
Works like a charm and all done on one line of ColdFusion.
4 Responses for "Find list elements using Regular Expressions"
Referencing Rpuesh Kumar “Extend CF Native Objects” post (http://coldfused.blogspot.com/ and http://www.blogger.com/comment.g?blogID=19056005&postID=116861460940707835). You might be able to do this much easier with the “built in” Contains() method of the Array object.
Well, I’d have a hard time accepting that it would be “easier” since I was able to do it in one CF statement. However, considering a very large list of values, perhaps it would be more efficient to convert to arrays and use contains().
I see a failure mode for your code:
I dont’ have a CF server handy to test, but I’m pretty sure this will return true, even though 3.25.178.4 isn’t in your large list, because it matches 63.25.178.45
VERY good catch, Adam. In light of this, I defer to Andy’s link to using native Java List functions for comparison – which can also be done in one line of CF code…
<cfset allElementsInLargeList = ListToArray(largeList).containsAll(ListToArray(smallList))>
Leave a reply