1

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

1 Answer 1

5

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!
}
Sign up to request clarification or add additional context in comments.

6 Comments

Also I believe running the exec() command on the regex option is actually faster and it gives you more results data, instead of just an array of matches.
Can you look at the edit I posted? I removed toString(), but still get a null, which should only happen when no pattern is passed at all.
Same with exec(), Is there something obviously wrong with the expression?
The flash docs are wrong. You get a NULL object if no match is made. I just tested your second example, it doesn't match because you have the ^ symbol which means it must be the start of the line, THEN a number or letter of any case. That doesn't exist in your example. Remove the hat, it works fine and traces the results.
To answer your question yes there is something wrong with the format of the expressions. Code tested with corrected expressions works fine. Check my updated answer you need to install regexr and use it to write your regex its a live regex editor.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.