AS3 RegEx returns null

≯℡__Kan透↙ 提交于 2019-12-24 06:43:46

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/5702436/as3-regex-returns-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!