Get an array of all Numbers inside a String - actionscript-3

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

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.

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?! :)

Related

Kotlin - How to make a for loop that iterate and return multiple values

I created a function that iterates by a if statement over a list in order to find a match, when found I wanted to return the match value, but it only happen once, the return statements are at the end of the function and the if statement.
The question is, How can I avoid that this function stops after the first match?, is there another way?, other functions that im not using?
When i run this code I get this:
Anything
Not a match
Not a match
Here is my code:
class Class1(var self: String,var tipo: String,var element: String)
var test_class = Class1("","","")
fun giver(){
test_class.self = "Anything"
test_class.tipo = "Something"
test_class.element = "Nothing"
}
class Funciones(){
fun match_finder(texto: String): Any{
var lista = listOf<String>(test_class.self,test_class.tipo,test_class.element)
var lista_de_listas = listOf<String>("test_class.self","test_class.tipo","test_class.element")
var count = -1
var variable = ""
for (i in lista_de_listas){
count = count + 1
println(count)
if (texto == i){
lista_de_listas = lista
var variable = lista_de_listas[count]
return variable
}
}
return "Not a match"
}
}
fun main(){
giver()
var x = "test_class.self"
var z = "test.class.tipo"
var t = "test.class.element"
var funcion = Funciones()
var y = funcion.match_finder(x)
var c = funcion.match_finder(z)
var r = funcion.match_finder(t)
println(y)
println(c)
println(r)
}
You have some typos in your example. You query for test.class.tipo but in your lista_de_listas you have test_class.tipo with underline. The same is true for test.class.element.
But you should consider to use a Map instead of two list to the lookup:
fun match_finder(texto: String): Any{
val map = mapOf(
"test_class.self" to test_class.self,
"test_class.tipo" to test_class.tipo,
"test_class.element" to test_class.element
)
return map.getOrDefault(texto,"Not a match")
}

Hash txt strings in GAS, incorrect line ending

I want hash (md5) some txt strings in GAS, and have a problem, may be
incorrect line ending.
Example:
test
test
correct hash 76ce9f441de2ed5de337d391ad4516b7
using GAS i getting wrong hash: e8230113fbba92427c1c41cf34a80c13
function test() {
var data = 'test\
test';
Logger.log(data.MD5());
return (data.MD5());
}
String.prototype.MD5 = function(charset, toByte) {
charset = charset || Utilities.Charset.UTF_8;
var digest = Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, this, charset);
if (toByte) return digest;
var __ = '';
for (i = 0; i < digest.length; i++) {
var byte = digest[i];
if (byte < 0) byte += 256;
var bStr = byte.toString(16);
if (bStr.length == 1) bStr = '0' + bStr;
__ += bStr;
}
return __;
}
As already #Ameen mentioned you are checking different strings
function test(){
var s1 = 'test\ntest';
var s2 = 'test\r\ntest';
Logger.log(s1.MD5() === '76ce9f441de2ed5de337d391ad4516b7');
Logger.log(s2.MD5() === '76ce9f441de2ed5de337d391ad4516b7');
}
[19-03-22 18:03:11:441 MSK] false
[19-03-22 18:03:11:442 MSK] true
A string containing "\r\n" for non-Unix platforms, or a string containing "\n" for Unix platforms.
It seems you're working under Windows.

How can I order my string in as3

A complex question :
I've got this code (not the complete code, but the essentials for the question, I think) :
var $pmm:String;
var $pms:String;
var $bmm:String;
var $bms:String;
function get haute1():String { return $pmm; };
function get haute2():String { return $pms; }
function get basse1():String { return $bmm; };
function get basse2():String { return $bms; };
accueil.todayHaute_txt.htmlText = haute1;
accueil.todayBasse_txt.htmlText = basse1;
accueil.todayHauteSecond_txt.htmlText = haute2;
accueil.todayBasseSecond_txt.htmlText = basse2;
"haute1" is an hour (in 24h format). Something like "13h25".
It changes everyday.
Question : How can put them in ascending order in AS3 ?
Example : If haute1 = 15h20, haute2= 6h00, basse1= 11h and basse2 = 17h, the function would put them in this order :
"haute2", then "basse1", then "haute1" and finally "basse2".
Thx
EDIT
I add this code that I have. is it helping you ?
/ Assigns hours and tidal heights
$pmm = convdateheure($tpbs[1 + $deltapm]);
$pms = convdateheure($tpbs[3 + $deltapm]);
$bmm = convdateheure($tpbs[2 - $deltapm]);
$bms = convdateheure($tpbs[4 - $deltapm]);
function convdateheure($valeur:Number):String
{
var $heure:Number = Math.floor($valeur);
var $minute:Number = Math.floor(Math.floor(($valeur - Math.floor($valeur)) * 100) * 0.6);
var hoursLabel:String = "", minsLabel:String = "";
if ($heure == 24) $heure = 0; // Check if at the 24 hour mark, change to 0
if ($heure < 10) hoursLabel += "0" + $heure.toString(); else hoursLabel = $heure.toString();
if ($minute < 10) minsLabel += "0" + $minute.toString(); else minsLabel = $minute.toString();
return hoursLabel + ":" + minsLabel;
}
If you want to order some dates written in some String format:
One way would be, depending on you date string format, just to push them into array and sort them as strings, then read them all.
Another way would be to first parse those strings into Date instances, and push their Date.time property to array, sort it, then do reverse: parse all time values from sorted array into new Date instances then use Date.toString or similar.
Assuming that $valuer is a numerical value:
var timesArray:Array = new Array();
var convertedTimesArray:Array = new Array();
function sortTimes():void{
timesArray.push($valuer);
timesArray.sort(Array.NUMERIC);
}
function convertTimes():void{
convertedTimesArray = []; // clear the array
for (var i:int = 0; i < timesArray.length; i++){
var s:String = convdateheure(timesArray[i]);
convertedTimesArray.push(s);
}
}
That should give you one array of actual times, sorted in numerical order, and one array sorted in the same numerical order, but converted to String values using your function.

I have a function that changes months into numbers, but I'd like to add 0 before the month's number

I have a date like:
19/août/2016 (août = august)
And I have the following function which changes the month into a number:
function swapMonthForNumber(str:String):String {
//do the same line of code for every item in the array
for(var i:int=0;i<months.length;i++){
//i is the item, which is 0 based, so we have to add 1 to make the right month number
str = str.replace(months[i],String(+i+1));
}
//return the updated string
return str;
}
str = swapMonthForNumber(mySharedObject.data.theDate);
trace("Php will use this date :"+str);
So str will be 19/8/2016, but I want str to be 19/08/2016 (adding a 0 before the 8).
How can I do this?
Check out the reference of the Date class!
If forgot to mention this link : flash.globalization.DateTimeFormatter
DateTimeFormatter(requestedLocaleIDName:String, dateStyle:String = "long", timeStyle:String = "long")
Here is an example.
import flash.globalization.DateTimeFormatter;
var df:DateTimeFormatter = new DateTimeFormatter(LocaleID.DEFAULT, DateTimeStyle.SHORT, DateTimeStyle.NONE);
var currentDate:Date = new Date(2016,7,19);
var shortDate:String = df.format(currentDate);
trace (shortDate);
// output : 19/08/2016
DateTimeStyle
LocaleID
Adding leading zeros to a number is commonly called zero padding.
Below is a function to do this, from the answer here.
public function zeroPad(number:int, width:int):String {
var ret:String = ""+number;
while( ret.length < width )
ret="0" + ret;
return ret;
}
In your swapMonthForNumber function, in the for loop, swap the code for this:
var month = zeroPad(i + 1, 2);
str = str.replace(months[i], month);

How I find that string contain a character more then 6 time in Flex?

I want to implement an alogorithm/validation. How can I find out if a string contains a specific character more than 6 times in Flex ?
There are 2 ways, I can think of:
Use RegExp and .replace() like this:
var ch:String = "a"; //Character, that must be checked
var text:String = "This is an example to show how many times '"+ch+"' occured.";
//Matches non-`ch` characters
var regexp:RegExp = new RegExp("[^"+ch+"]","g");
//Replacing non-`ch` characters with empty string
var timesOccured:Number = text.replace(regexp,"").length;
trace(text, ": " ,timesOccured );
Use RegExp and .match() like this:
var ch:String = "a"; //Character, that must be checked
var text:String = "This is an example to show how many times '"+ch+"' occured.";
//Matches `ch` characters
var regexp:RegExp = new RegExp(ch,"g");
var matches:Array = text.match(regexp);
var timesOccured:Number = 0;
//`matches` can be 'null', so we are performing additional check
if( matches ){
timesOccured = matches.length;
}
trace(text, ": " ,timesOccured );
Now when you have timesOccured, you could easily do your validation:
if( timesOccured > 6 ){
//Do some stuff
}else{
//Do other stuff
}
Warning: If your ch is a special character for Regular Expression, like a .,+,(,],\,etc..., you need to escape it, before passing it to regexp variable:
ch = ch.replace(new RegExp("[.*+?|()\\[\\]{}\\\\]", "g"), "\\$&");
a simpler alternative to regular expressions can be the following:
var str:String = "This is an example to show how many...";
//find occurrences for character 'a'
trace("Ocurrences:" + str.split('a').length-1);