如何在字串中獲取所有數字(如果有)的陣列?
這樣:
var txt: String = "So 1 and 22 plus33 = (56) and be4 100 is 99!";
trace(getNumAry(txt));
輸出這個:
1,22,33,56,4,100,99
uj5u.com熱心網友回復:
正則運算式是您正在尋找的答案。你需要這樣的東西(未經測驗,但這個想法應該是正確的):
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);
如果沒有詳細的注釋,代碼可以簡化為這個簡單的單行代碼:
var result:Array = "So 1 and 22 plus33 = (56) and be4 100 is 99!".match(/\d /g);
請記住,此搜索將回傳一個String陣列,因此如果您希望它們為int ,則需要采取一些額外的步驟。
uj5u.com熱心網友回復:
這是我想出的作業解決方案:
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));
}
如果你運行這個:
var txt: String = "So 1 and 22 plus33 = (56) and be4 100 is 99!";
trace(getNumAry(txt));
這是您獲得的逐步跟蹤:
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
想知道有沒有更簡單的方法?!:)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/511809.html
