Utility Function: PatternReplace()

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") />

 

Comments

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.

Post a job. Find one. authenticjobs.com

Interested in becoming a sponsor? Contact me.