RegExp Constructor Issue
The Flex documentation is a a little misleading in regards to the RegExp Constructor. Livedocs has this to say:
public function RegExp(re:String, flags:String)
Lets you construct a regular expression from two strings. One string defines the pattern of the regular expression, and the other defines the flags used in the regular expression.
Notice the lack of a default value for the flags argument? One would think that would mean you should get a compilation error if you don't supply both arguments to the constructor. However, both of these compile without error:
var regExpA:RegExp = new RegExp("^http://www.google.com/(.*)$"); var regExpB:RegExp = new RegExp("^http://www.google.com/(.*)$", "");
I would expect the first one to cause this error:
1136: Incorrect number of arguments. Expected 2.
It would be nice if the documentation was just wrong and you didn't need to supply the second argument to the constructor. The problem is the two regular expressions behave differently! The missing flags argument causes the regular expression to do funky stuff, which is not the same as passing in the empty string. For example look at the output of this little example:
trace(regExpA.test("http://www.google.com/")); trace(regExpA.test("http://www.google.com/webhp?hl=en")); trace(regExpB.test("http://www.google.com/")); trace(regExpB.test("http://www.google.com/webhp?hl=en")); // Output // true // false // true // true
That false shouldn't be there! The funky stuff that is going on behind the scenes is that without the second argument to the constructor it is looking at the regular expression string itself to set the flags. In this case g appears after a //, which is the way you specify the global flag in a RegExp literal. To confirm this, look at the string version of each RegExp:
trace(regExpA); trace(regExpB); // Output // /^http://www.google.com/(.*)$/gm // /^http://www.google.com/(.*)$/
Cool, we also picked up the multiline flag since m also appears! The problem only occurs if you have more than one / followed by one of the regular expression flags. The two slahses don't need to be next to each other just having two anywhere in the string followed by other text can cause the problem. In general you are probably better using RegExp literals, but if you do use the RegExp constructor be sure to supply both arguments, even if the second one is just the empty string.