Home > other >  Get an array of all Numbers inside a String
Get an array of all Numbers inside a String

Time:09-10

How can I get an array of all Numbers (if any) inside a String?

So that this:

var txt: String = "So 1 and 22 plus33 = (56) and be4 100 is 99!";
trace(getNumAry(txt));

Output this:

1,22,33,56,4,100,99

CodePudding user response:

This is the working solution I have come up with:

function getNumAry(txt:String):Array {
    var res:Array = new Array();            

    var str: String = ""
    //Non-Number Chars to Dot
    for (var i:int = 0; i < txt.length; i  ) {
        if(isNum(txt.substr(i,1))){
            str  = txt.substr(i, 1);
        } else {
            str  = ".";
        }
    }
    trace(txt);
    trace(str);
    //Spaces to Dot
    str = str.split(" ").join(".")
    trace(str);
    //Dots to Single Dot
    while (str.indexOf("..") != -1) {
        str = str.split("..").join(".");                
    }           
    trace(str);
    //Remove first Dot
    if (str.indexOf(".") == 0 ) {
        str = str.substr(1);
    }           
    trace(str);
    //Remove last Dot
    if (str.lastIndexOf(".") == str.length-1 ) {
        str = str.substr(0,str.length-1);
    }               
    trace(str);
    //get Nums if any
    if (str != "" && str != ".") {              
        res = str.split(".");
    }

    return res;
}

function isNum(chr: String):Boolean {
    return !isNaN(Number(chr));
}

if you run this:

var txt: String = "So 1 and 22 plus33 = (56) and be4 100 is 99!";
trace(getNumAry(txt));

This is the step-by-step trace of what you get:

So 1 and 22 plus33 = (56) and be4 100 is 99!
.. 1 ... 22 ....33 . .56. ... ..4 100 .. 99.
...1.....22.....33....56........4.100....99.
.1.22.33.56.4.100.99.
1.22.33.56.4.100.99.
1.22.33.56.4.100.99
1,22,33,56,4,100,99

Wondering if there has been an easier way?! :)

CodePudding user response:

Regular Expressions is the answer you are looking for. You need something like that (not tested, yet the idea should be correct):

var source:String = "So 1 and 22 plus33 = (56) and be4 100 is 99!"

// The pattern \d  instructs to find one or more consequent decimal digits.
// That also means that before each match there will be a non-digit character
// or the beginning of the text, and after the match will also be a non-digit
// or the end of the text.
// The [g]lobal flag is for searching multiple matches.
var re:RegExp = /\d /g;

// Search for all the matches.
var result:Array = source.match(re);

Without the elaborate commenting the code could be reduced to this simple one-liner:

var result:Array = "So 1 and 22 plus33 = (56) and be4 100 is 99!".match(/\d /g);

Please keep in mind that this search will return an Array of Strings so if you want them as ints you need to take some additional steps.

  • Related