RegExp In An Anonymous Function
Regular expressions are downright handy for a variety of string processing tasks. They are so handy that they are built straight in to the language in the form of the /regexpgoeshere/ syntax. Well, usually…
The above is true except for one weird case. Consider these simple functions:
function foo(): RegExp { return /^monkey$/; } var bar:Function = function(): RegExp { return /^monkey$/; };
They are, of course, almost exactly the same. The former works just fine, but the latter inexplicably blows up at compile time:
Error: Syntax error: expecting identifier before div. return /^monkey$/; ^
The “div” it is talking about is the first slash in the regular expression. MXMLC is not recognizing regular expressions defined in this way withing anonymous functions. I don’t know why it draws a distinction between anonymous functions and named ones, but it does. Fortunately, the workaround is simple:
var bar:Function = function(): RegExp { return new RegExp("^monkey$"); };
All you have to do is use the RegExp constructor instead. The two are essentially equivalent anyhow, so feel free to use whichever you like wherever you like so long as you always use the RegExp constructor within anonymous functions.
#1 by hanamura on October 2nd, 2009 ·
This also works fine in my environment.
return (/^monkey$/);
#2 by jackson on October 2nd, 2009 ·
Whoa. It makes the syntax even weirder, but still a nice workaround so you can use the syntax sugar. Thanks for the tip!
#3 by Jan on October 2nd, 2009 ·
This way very simple and clean:
public static const UPPER : RegExp = /[A-Z]/;
public static const LOWER : RegExp = /[a-z]/;
Usage:
UPPER.test(“Hello world”)
#4 by jackson on October 2nd, 2009 ·
Good point. If you’re going to use the syntax sugar, you have a constant regular expression anyhow. Thanks for pointing this out.
#5 by dVyper on October 5th, 2009 ·
I wonder if anyone has done any speed comparisons between using the RegExp constructor and not using it…
#6 by jackson on October 5th, 2009 ·
This piqued my interest so I tried it out:
And the results:
So I guess it really is just syntax sugar.