Utility Function: PatternReplace()
- December 14, 2008 5:30 AM
- Utility Function
- Comments (0)
Ok, so this one is neat. It takes a pattern and a string, extracts the groups, and then injects the groups into a replacement string based on group numbers. The notation "$x" is used to indicate replacement position, where x is the group number you want to use. The neat thing is that position 0 always corresponds to the whole original string.
<cffunction name="PatternReplace" output="false" returntype="string">
<cfargument name="pattern" type="string" required="true" />
<cfargument name="string" type="string" required="true" />
<cfargument name="replacement" type="string" required="true" />
<cfset var local = StructNew() />
<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) >
<cfreturn local.matcher.replaceAll(arguments.replacement) />
</cffunction>
Example:
<!--- This results in "google dog" --->
<cfset x = PatternReplace("d(o)(g)", "dog", "$2$1$1$2le $0") />