Question

The following code is returning an error on Mid, saying the third argument is -2 - so it thinks the length is 0. We're totally stumped as to how this could happen. The code looks for values between curly braces and strips them out. Can you think of a way to break this? Str can be anything - we don't know, it's not supplied by us - so that's the var you want to break.

str = "Here's a string with {EmailAddy} and maybe some {otherVariables}";
start = 1;
pos = 0;
length = 0;
tokens = ArrayNew(1);
while(true) {
    x = REFind("\{\w*\}", str, start, true);
    pos = x.pos[1];
    length = x.len[1];

    if (pos == 0) {
        break;
    } else {
        // get the token, trimming the curly brackets
        token = mid(str, pos+1, length-2);  
        arrayAppend(tokens, token);
        start = pos + length;
    }
}
WriteDump(tokens);
Was it helpful?

Solution

You don't need lookbehind:

var Tokens = rematch( "\{\w*(?=\})" , Arguments.Str );

for ( var i = 1 ; i LTE ArrayLen(Tokens) ; i++ )
    Tokens[i] = Tokens[i].substring(1);

return Tokens;


And that code should also give you a clue as to the most likely cause of the code breaking, in that you've probably got it in a function in a persisted component, but (without any scoping) everything is going in the component's variables scope, and thus it's not thread-safe and - with multiple calls under load - the variables involved are liable to get corrupted.

This is a general issue you should be looking for throughout the code - generally the first assignment for every variable inside a function should be prefixed with either the var keyword (or explicitly the local. scope) to ensure it it local to that function and not global the the component. (Except of course in the instances when a global variable is what is desired.)


Oh, and if you ever do actually want/need to use lookbehind in CF, I've made cfRegex, a library that wraps Java's more powerful regex engine, providing support for lookbehind (with limited-width), and with a (hopefully) easy to use and consistent set of functions for interacting with it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top