Skysplitter MC
Skysplitter MC

Reputation: 13

AS3: Get all substrings from a string in a specified array

This is not a duplicate because all the other questions were not in AS3.

Here is my problem: I am trying to find some substrings that are in the "storage" string, that are in another string. I need to do this because my game server is sending the client random messages that contain on of the strings in the "storage" string. The strings sent from the server will always begin with: "AA_".

My code:

private var storage:String = AA_word1:AA_word2:AA_word3:AA_example1:AA_example2";
    if(test.indexOf("AA_") >= 0) {
        //i dont even know if this is right...
    }
}

If there is a better way to do this, please let me know!

Upvotes: 1

Views: 307

Answers (3)

Sly_cardinal
Sly_cardinal

Reputation: 12993

Regular Expressions are the right tool for this job:

function splitStorage(storage: String){
    var re: RegExp = /AA_([\w]+):?/gi;

    // Execute the regexp until it 
    // stops returning results.
    var strings = [];
    var result: String;
    while(result = re.exec(storage)){
        strings.push(result[1]);
    }
    return strings;
}

The important part of this is the regular expression itself: /AA_([\w]+):?/gi This says find a match starting with AA_, followed by one-or-more alphanumeric characters (which we capture) ([\w]+), optionally followed by a colon.

The match is then made global and case insensitive with /gi.

If you need to capture more than just letters and numbers - like this: "AA_word1 has spaces and [special-characters]:" - then add those characters to the character set inside the capture group.

e.g. ([-,.\[\]\s\w]+) will also match hyphen, comma, full-stop, square brackets, whitespace and alphanumeric characters.

Upvotes: 0

leetwinski
leetwinski

Reputation: 17859

Also you could do it with just one line, with a more advanced regular expression:

var storage:String = 'AA_word1:AA_word2:AA_word3:AA_example1:AA_example2';
const a:Array = storage.match(/(?<=AA_)\w+(?=:|$)/g);

so this means: one or more word char, preceeded by "AA_" and followed by ":" or the end of string. (note that "AA_" and ":" won't be included into the resulting match)

Upvotes: 0

akmozo
akmozo

Reputation: 9839

Why not just using String.split() :

var storage:String = 'AA_word1:AA_word2:AA_word3:AA_example1:AA_example2';

var a:Array = storage.split('AA_'); 
// gives : ,word1:,word2:,word3:,example1:,example2

// remove the 1st ","
a.shift();                          

trace(a);  // gives : word1:,word2:,word3:,example1:,example2

Hope that can help.

Upvotes: 1

Related Questions