views:

1308

answers:

2

I try to create a project with use a Split in AC2.

this I have

    in_pers = 3x5+5x3+6x8;

var tmp:Array = in_pers.split("+");

trace(tmp);  //output ==  3x5, 5x3, 6x8

but, how if in_pers = 3x5+5x3-6x8-4x2;

how can I get the result 3x5, 5x3, 6x8, 4x2

how to use the split with two delimiter.

Best regard..

+1  A: 

Sadly, AS2 has no native understanding of regular expressions. To use RegExp, you'd have to move to AS3, or find a regular expression class written for AS2...there are some out there.

I think for this purpose you'd need to create a custom function. I'm not sure the one I've created below is the best...a bit kludgy and maybe not the most performant, but I think it does essentially what you need.

var in_pers:String = "3x5+5x3-6x8-4x2";
var tmp:Array = multiSplit(in_pers, ["+", "-"]);
trace (tmp);

function multiSplit(str:String, delimiters:Array):Array
{
    /* create an array to return */
    var resultArray:Array = [];

    /* loop through the string */
    var a:Number = 0;
    while (a < str.length)
    {
     var first:Number = str.length;
     var bLen:Number = delimiters.length;

         /* loop through the delimiters */
     for (var b:Number = 0; b < bLen; b++)
     {
      var delimiter:String = delimiters[b];

          /* find the first delimiter */
      var index:Number = str.indexOf(delimiter, a + 1);

      if (index != -1 && index < first)
       first = index;
     }
     if (first == a)
      break;
     /* Add the substring to the return array */
     resultArray.push(str.substring(a, first));
     a = first+1;
    }
    return resultArray;
}
Wikiup
+1  A: 

There is a much simpler way to do what wikiup suggested:

function strReplace( haystack:String, needle:String, replacement:String ):String
{
    var tmpA:Array = haystack.split( needle );
    return tmpA.join( replacement );
}

function multiSplit( haystack:String, needles:Array ):Array
{
    // generate a unique String for concatenation.
    var salt:String = String( Math.random() ); //replace with anything you like

    // Replace all of the strings in the needles array with the salt variable
    for( var i:Number = 0; i < needles.length; i++ )
    {
        haystack = strReplace( haystack, needles[ i ], salt );
    }

    //haystack now only has the objects you want split up concatenated by the salt variable.
    //split haystack and you'll have your desired result.
    return haystack.split( salt );
}

Not only is this smaller, it is also faster (while takes a lot longer than for( i = 0; i < val; i++ ) (look up iteration vs. recursion) ).

Christopher W. Allen-Poole