且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

AS3正则表达式返回null

更新时间:2022-11-12 10:42:50

更新

如果你打算在闪光灯与正则表达式的工作,这个工具是一个必须具备的:

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

原来的答案

不要使用的toString(),你那么做文字搜索,其中包括增加你所有的正则表达式的格式,包括标志的。做:

  str.match(cleanRegExp);
 

其实正确的方法是将引用返回的对象,像这样:

  VAR结果:阵列= str.match(cleanRegExp);

如果(结果!= 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]);

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