Utility Function: PatternExtract()

Yet another Pattern based utility function. PatternExtract() takes a pattern and gives you make a structure with values based on the groups. Additional function arguments (beyond pattern and string) are used to determine the keys (in order) that match with the groups.

<cffunction name="PatternExtract" output="false" returntype="struct">
    <cfargument name="pattern" type="string" required="true" />
    <cfargument name="string" type="string" required="true" />

    <cfset var returnValue = StructNew() />
    <cfset var array = Duplicate(arguments) />

    <cfset ArrayDeleteAt(array, 1) />
    <cfset ArrayDeleteAt(array, 2) />

    <cfif IsSimpleValue(arguments.pattern)>
        <cfset arguments.pattern = CreateObject("java", "java.util.regex.Pattern").compile(arguments.pattern) />
    </cfif>
    
    <cfset local.matcher = arguments.pattern.matcher(arguments.string)>

    <cfif local.matcher.matches()>
        <cfset local.groups = local.matcher.groupCount() />
        <cfloop from="1" to="#local.groups#" index="x">
            <cfset returnValue[array[x]] = local.matcher.group(x) />
        </cfloop>
    </cfif>

    <cfreturn returnValue />
</cffunction>

I coded this in a hurry, so yeah its a little sloppy. I'll try and update this post with a more refined version.

 
Comments are not allowed for this entry.
Jon Hartmann, July 2011

I'm Jon Hartmann and I'm a Javascript fanatic, UX/UI evangelist and former ColdFusion master. I blog about mysterious error messages, user interface design questions, and all things baffling and irksome about programming for the web.

Learn more about me on LinkedIn.