Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AS3 : RegExp exec method in loop problem

I need some help about RegExp in AS3.

I have a simple pattern :

patternYouTube = new RegExp ( "v(?:\/|=)([A-Z0-9_-]+)", "gi" );

This pattern is looking for the youTube id video.

For example :

var tmpUrl : String;    
var result : Object;
var toto : Array = new Array();
toto = ["http://www.youtube.com/v/J-vCxmjCm-8&autoplay=1", "http://www.youtube.com/v/xFTRnE1WBmU&autoplay=1"];
var i : uint;

for ( i = 0 ; i < toto.length ; i++)
{
     tmpUrl = toto[i];
     result = patternYouTube.exec ( tmpUrl );
     if ( result.length != 0 && result != null )
     {
         trace(result);
     }
}

When i == 0, it works perfectly. Flash returns me : v/J-vCxmjCm-8,J-vCxmjCm-8

When i == 1, it fails. Flash returns me : null

When I revert the two strings in my array such as :

toto = [ http://www.youtube.com/v/xFTRnE1WBmU&autoplay=1, http://www.youtube.com/v/J-vCxmjCm-8&autoplay=1 ];

When i == 0, it works perfectly : Flash returns me : xFTRnE1WBmU

When i == 1, it fails : Flash returns me : null

Do you have any idea about the problem in the loop ?

like image 692
Boun Avatar asked Feb 28 '23 09:02

Boun


1 Answers

That's what g​lobal RegExps do in JavaScript/ActionScript. You exec them once, you get the first match, exec them again and get the second match. With a g RegExp you have to keep calling it again until you've got through all the matches. Then you'll get null and the search will reset to the start of the string.

It's a weird interface, but that's what we're stuck with. If you don't want this behaviour, omit the 'g' flag from the new RegExp constructor. Then you'll get only the first match, every time.

like image 117
bobince Avatar answered Mar 08 '23 00:03

bobince