Search code examples
stringcoldfusion

ColdFusion - Last Occurence of a string using RefindNoCase


I am using RefindNoCase to find the last occurrence of a string. This is the code I am using:

<cfset result= REfindNoCase('-[A-Z]{3}', variables.textBeforeFirstName, 1, "true")>

This is supposed to return an array with positions and length for each occurrence but it will return only the first one. On the specific string I have 3 occurrences and I will need only the last one. Because I wont know how many occurrences each string has, how I am supposed to get the last one?


Solution

  • I found a manual solution as workaround because it seems there is no function for Coldfusion to match all cases. What I did was to create a loop searching for the substring and if it finds it then it removes the previous text from the current string. The loops stops when there is no other occurrences in the remaining string so the last occurrence in your variable is what you looking for. This is the code:

        <cfloop condition="continueParse eq true">
    
            <cfset airportService= REfindNoCase('-[A-Z]{3}', variables.textBeforeFirstName, 1, "true")>
    
            <cfif airportService.len[1] gt 0>
    
                <cfset variables.airportServiceName = #mid(variables.textBeforeFirstName,airportService.pos[1],airportService.len[1])#>
    
                <cfset variables.textBeforeFirstName = #right(variables.textBeforeFirstName,#len(variables.textBeforeFirstName)#-(airportService.pos[1]+airportService.len[1]))#>   
                #variables.airportServiceName#<br/>
    
            <cfelse>
                <cfset continueParse = false>
            </cfif>
        </cfloop>