Utility Function: PatternExtract()
- January 9, 2009 5:30 AM
- Utility Function
- Comments (0)
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.
<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>