AS3: RegExp exec method in a loop

I need help with RegExp in AS3.

I have a simple template:

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

This template searches for youTube video.

For instance:

 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 fine. Flash brings me back: v/J-vCxmjCm-8,J-vCxmjCm-8

When I == 1, it fails. Flash brings me back: null

When I return two lines 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 fine: Flash returns me: xFTRnE1WBmU

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

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

+4
source share
2 answers

What does 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 g RegExp, you must continue to call him again until you have completed all the matches. Then you will get null , and the search will reset to the beginning of the line.

This is a weird interface, but this is what we are stuck with. If you do not want this behavior, omit the 'g' flag from the new RegExp constructor. Then you get only the first match each time.

+5
source

bobince is completely right, but you can also set the lastIndex property to 0 before calling exec ().

 patternYouTube.lastIndex = 0; 

Now you can have your flag flag cake and eat it too ... or uh, something like this ...

+3
source

Source: https://habr.com/ru/post/1304276/


All Articles