Search code examples
coldfusioncoldfusion-10

Find Multiple Occurrences in String using REFind


I'm trying to get ColdFusion's REFindNoCase function to return multiple instances of a matching string but can't seem to get it to work:

<cfset string2test="cfid skldfjskdl cfid sdlkfjslfjs cftoken dslkfjdslfjks cftoken">
<cfset CookieCheck =  REFindNoCase( 'CFTOKEN', string2test, 1, true)>
<cfif arrayLen( CookieCheck['LEN'] ) gt 1>
    MULTIPLE CFTOKEN!
</cfif>

Is there a regular expression magic syntax I need to use to make it search for more than 1?


Solution

  • The syntax of the code above will create structure with arrays (LEN,POS) for pattern match and subexpressions. RegEx subexpressions are within parenthesis in the pattern. The 'CFTOKEN' pattern does not contain a subexpression.

    I don't think that REFindNoCase will do what you are wanting to accomplish.

    For example, if you use '.*?(cftoken)' as the pattern:

    <cfset CookieCheck =  REFindNoCase('.*?(CFTOKEN)', string2test, 1, true)>
    

    (CFTOKEN) is a subexpression. If you remove the "?", the information for the last occurrence of 'cftoken' is returned.

    The values in the first array items will match the entire pattern up to the first 'cftoken' (the first 40 characters of the string). The second set of values will identify the 'cftoken' string that was found in first match (first 40 chars).

    Because the statement in the example does not include subexpressions, only the first pattern match is returned.

    If you need to check to see if something is listed multiple times or you don't need to manipulate the original string, I would recommend using REMatchNoCase(). It returns an array of pattern matches but without the position info.