shanethehat
shanethehat

Reputation: 15580

AS3 RegEx returns null

Can anyone explain why the code below traces null when on the timeline?

var cleanRegExp:RegExp = /^[a-zA-Z0-9]+(\b|\/)/;
var str:String = "/num83r5/and/letters/4/A/";
trace(str.match(cleanRegExp.toString()));

I've read the documentation, so I'm pretty sure that I'm declaring the RegEx correctly and that String.match() should only return null when no pattern is passed in, otherwise it should be an array with 0+ elements. I suspected a badly written expression, but surely that should still return an empty array?

EDIT: Both these trace "no matches" instead of either 5 or 0, depending on the expression being correct:

var cleanRegExp:RegExp = /^[a-zA-Z0-9]+(\b|\/)/;
var str:String = "/num83r5/and/letters/4/A/";
var res:Array = str.match(cleanRegExp);
trace((res == null) ? "no matches" : res.length);

And:

var cleanRegExp:RegExp = /^[a-zA-Z0-9]+(\b|\/)/;
var str:String = "/num83r5/and/letters/4/A/";
var res:Object = cleanRegExp.exec(str);
trace((res == null) ? "no matches" : res[0]);

Upvotes: 1

Views: 1130

Answers (1)

user562566
user562566

Reputation:

UPDATE

If you're going to work in flash with regex, this tool is a must-have:

http://gskinner.com/RegExr/
http://gskinner.com/RegExr/desktop/

ORIGINAL ANSWER

Don't use toString(), you're then doing a literal search, which will include the addition of all of your regex formatting, including flags. Do:

str.match(cleanRegExp);

In fact the proper method is to reference the returned object like so:

var results:Array = str.match(cleanRegExp);

if(results != null){
     //We have a match!
}

Upvotes: 5

Related Questions