开发者

AS3 RegEx returns null

开发者 https://www.devze.com 2023-02-26 21:24 出处:网络
Can anyone explain why the code below traces null when on the timeline? var cleanRegExp:RegExp = /^[a-zA-Z0-9]+(\\b|\\/)/;

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]);


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!
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号