Search code examples
regexactionscript-3apache-flex

Split with Regex creating empty strings


I'm trying to generate an array of elements that are either text or an "image block".

var str : String = "";

for (var i : int = 0; i < 100; i++)
{
    str += (Math.random() > .5) ? "<img>amazed</img>" : "<img>happy</img>";
}

var arr : Array = str.split(/(<img>\w+<\/img>)/);

I want the array to have a length of 100 and for each element in the array to reflect either <img>amazed</img> or <img>happy</img>. Instead, the length is 201 and every other element is an empty String.

Is there a simple way to change the regex to avoid doubling the size of the array?


Solution

  • String.split(...) splits the given string by the provided separator rather then searches for them.

    In order to find all matches with RegEx you need to use String.match(...) method:

    var S:String = "";
    
    for (var i:int = 0; i < 100; i++)
    {
        S += (Math.random > .5)? "<img>amazed</img>": "<img>happy</img>";
    }
    
    // Pay attention to the greedy 'g' flag, if you don't set it,
    // you will get the first match only as the result.
    var R:RegExp = /<img>\w+<\/img>/g;
    var A:Array = S.match(R);