Regular expression to parse the time-stamp string in ActionScript3 - regex

I am working on a project in ActionScript3. I have this function that parses a time-stamp string.
private function convertTimestampToNumber(timestamp:String):Number {
//YYYY-MM-DD HH:mm:SS:sss
var re:RegExp = /(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})\s(?P<hour>\d{2}):(?P<min>\d{2}):(?P<sec>\d{2})\.(?P<msec>\d{3})/;
var result:Array = re.exec(timestamp);
Alert.show(timestamp, "Timestamp string", Alert.OK);
return (10000000000000 * parseInt(result.year)
+ 100000000000 * parseInt(result.month)
+ 1000000000 * parseInt(result.day)
+ 10000000 * parseInt(result.hour)
+ 100000 * parseInt(result.min)
+ 1000 * parseInt(result.sec)
+ parseInt(result.msec));
}
This seems to work fine for all time-stamps except "2016-08-01 09:19:43.23". Here it throws an error:
[Fault] exception, information=TypeError: Error #1009: Cannot access a property or method of a null object reference.
I thought since the millisecond part of this time-stamp is only 2 chars long, it was throwing error. To fix this I changed the millisecond part of the regular expression to (?P<msec>\d{2|3}) thinking that now it would consider both 2-character and 3-character long millisecond as valid, but now it throws the same error on "2015-11-19 15:28:29.737".
What will be the correct regular expression that can consider both scenarios as valid?

Your change is almost right. What you can do is this:
(?P<msec>\d{1,3})
Which will match any number of milliseconds, from 1 digit (possible, though unlikely to appear) to 3.

I'm not sure to understand your question, but if you use de Date Class, you may format your result as you want.
Check and adapt the DateTimeFormatter code here bellow
And check for setDateTimePattern() method too.:
import flash.utils.getTimer;
import flash.globalization.DateTimeFormatter;
import flash.globalization.DateTimeStyle;
var currentTime = new Date();
function formatDate(date:Date) {
var dtf:DateTimeFormatter = new DateTimeFormatter("fr-FR");
// or new DateTimeFormatter("en-EN");
dtf.setDateTimePattern("yyyy-MM-dd hh:mm:ss");
var longDate:String = dtf.format(date);
trace(longDate)+getTimer();
//trace(" *** LocaleID requested=" + dtf.requestedLocaleIDName);
//trace(" *** Format requested (" + dtf.getDateTimePattern() + ")");
}
trace(" setDateTimePattern example");
formatDate(currentTime);
// output the current time formated as "yyyy-MM-dd hh:mm:ss"
// no Milliseconds avalaible now!
Just check the reference, and you'll find an answer AMO.
Hope this helps.

Related

Input Formatter Regex for simple mathematical calculation in Flutter/Dart

I want to ensure valid input on my text field where user can key in simple math expression for numbers up to 2 d.p such as "1.10 + 3.21 x 0.07". I am doing this through the adding regex to the input formatter constructor in the TextField class.
Following the regex example for 2 d.p here, I modified the code for my text field input formatter to include operators:
String dp = (decimalRange != null && decimalRange > 0)
? "([.][0-9]{0,$decimalRange}){0,1}"
: "";
String num = "($dp)|([0-9]{1,4}$dp)";
_exp = new RegExp(
"^($num){0,1}[-+x/]{0,1}($num){0,1}[-+x/]{0,1}($num){0,1}\$");
I am able to achieve "1.10 + 3.21 x 0.07", however, the user can also type invalid value into the textfield such as "1...10", "1.10 + 3..21". Any advice to improve the Regex above would be greatly appreciated!
Note that I also limit the user to key in a maximum of 3 decimal numbers. so "(2d.p)(operator)(2d.p)(operator)(2d.p)is the maximum limit.

Remove operations using regex [duplicate]

This question already has answers here:
How to find sum of integers in a string using JavaScript
(3 answers)
Closed 3 years ago.
I am getting a string back "1+2" and would like to remove the "+" and then add the numbers together.
Is this possible using Regex? So far I have:
let matches = pattern.exec(this.expression);
matches.input.replace(/[^a-zA-Z ]/g, "")
I am now left with two numbers. How would I add together?
"this.a + this.b"
Assuming the string returned only has '+' operation how about:
const sum = str.split('+').reduce((sumSoFar, strNum) => sumSoFar + parseInt(strNum), 0);
You cannot add two numbers using regex.
If what you have is a string of the form "1+2", why not simply split the string on the + symbol, and parseInt the numbers before adding them?
var str = "1+2";
var parts = str.split("+"); //gives us ["1", "2"]
console.log(parseInt(parts[0]) + parseInt(parts[1]));
If you don't always know what the delimiter between the two numbers is going to be you could use regex to get your array of numbers, and then reduce or whatever from there.
var myString = '1+2 and 441 with 9978';
var result = myString.match(/\d+/g).reduce((a,n)=> a+parseInt(n),0);
console.log(result); // 1 + 2 + 441 + 9978 = 10422
*Edit: If you actually want to parse the math operation contained in the string, there are a couple of options. First, if the string is from a trusted source, you could use a Function constructor. But this can be almost as dangerous as using eval, so it should be used with great caution. You should NEVER use this if you are dealing with a string entered by a user through the web page.
var myFormula = '1+2 * 441 - 9978';
var fn = new Function('return ' + myFormula);
var output = fn();
console.log(myFormula, ' = ', output); //1+2 * 441 - 9978 = -9095
A safer (but more difficult) course would be to write your own math parser which would detect math symbols and numbers, but would prevent someone from injecting other random commands that could affect global scope variables and such.

Convert Integer to String and Concatenate in PowerBI

Though question seems to be simple, I am trying to concatenate Integer and String by converting integer to string, My formula in DAX :
var storedata=450
var hours = QUOTIENT(storedata, 60)
var minutes = storedata - hours*60
Return
FORMAT(hours,"")+":"+FORMAT(minutes,"")
Format function throws error can't convert type string to type number
But as per the documentation format function converts number to string but here error is totally opposite.
How can I convert Integer to String and concatenate.
Thanks
You can use the function concatenate to return the result as a string:
Measure 4 = var storedata=450
var hours = QUOTIENT(storedata, 60)
var minutes = storedata - hours*60
Return
CONCATENATE(CONCATENATE(FORMAT(hours,""),":"),FORMAT(minutes,""))
This can solve your problem?

Nodejs - Extract a dynamic numerical value from an array of strings?

I have command output that has been stored in an array of strings, and this numerical value could or could not exist in a string, and if it does exit it can be any integer value. I've tried various methods with regex and parseInt, and I am not getting the desired effect, I believe because of the way the string is encoded. How have others gone about this in the past?
EDIT:
The issue is the string is coming back, encoded as UT8. So the initial string I get is this: disk: 40 Which I can reduce down to: 40 After that however, using a isNaN(decode_utf8(str)) Still produces a true for isNaN. I am not sure exactly how to overcome this
Try testing if a string is a number like this:
var toTest = "232";
if (!isNaN(+toTest)) {
var aNumber = +toTest
console.log('That is a number: ', aNumber)
if it must be a integer you could check like this:
// check if integer ...
var isInt = typeof aNumber === "number" && aNumber % 1 === 0;
}
If you are using latest JavaScript ES6 then isNumber is built in:
Number.isInteger(123) // true

Google sheet : REGEXREPLACE match everything except a particular pattern

I would try to replace everything inside this string :
[JGMORGAN - BANK2] n° 10 NEWYORK, n° 222 CAEN, MONTELLIER, VANNES / TARARTA TIs
1303222074, 1403281851 & 1307239335 et Cloture TIs 1403277567,
1410315029
Except the following numbers :
1303222074
1403281851
1307239335
1403277567
1410315029
I have built a REGEX to match them :
1[0-9]{9}
But I have not figured it out to do the opposite that is everything except all matches ...
google spreadsheet use the Re2 regex engine and doesn't support many usefull features that can help you to do that. So a basic workaround can help you:
match what you want to preserve first and capture it:
pattern: [0-9]*(?:[0-9]{0,9}[^0-9]+)*(?:([0-9]{9,})|[0-9]*\z)
replacement: $1 (with a space after)
demo
So probably something like this:
=TRIM(REGEXREPLACE("[JGMORGAN - BANK2] n° 10 NEWYORK, n° 222 CAEN, MONTELLIER, VANNES / TARARTA TIs 1303222074, 1403281851 & 1307239335 et Cloture TIs 1403277567, 1410315029"; "[0-9]*(?:[0-9]{0,9}[^0-9]+)*(?:([0-9]{9,})|[0-9]*\z)"; "$1 "))
You can also do this with dynamic native functions:
=REGEXEXTRACT(A1,rept("(\d{10}).*",counta(split(regexreplace(A1,"\d{10}","#"),"#"))-1))
basically it is first split by the desired string, to figure out how many occurrences there are of it, then repeats the regex to dynamically create that number of capture groups, thus leaving you in the end with only those values.
First of all thank you Casimir for your help. It gave me an idea that will not be possible with a built-in functions and strong regex lol.
I found out that I can make a homemade function for my own purposes (yes I'm not very "up to date").
It's not very well coded and it returns doublons. But rather than fixing it properly, I use the built in UNIQUE() function on top of if to get rid of them; it's ugly and I'm lazy but it does the job, that is, a list of all matches of on specific regex (which is: 1[0-9]{9}). Here it is:
function ti_extract(input) {
var tab_tis = new Array();
var tab_strings = new Array();
tab_tis.push(input.match(/1[0-9]{9}/)); // get the TI and insert in tab_tis
var string_modif = input.replace(tab_tis[0], " "); // modify source string (remove everything except the TI)
tab_strings.push(string_modif); // insert this new string in the table
var v = 0;
var patt = new RegExp(/1[0-9]{9}/);
var fin = patt.test(tab_strings[v]);
var first_string = tab_strings[v];
do {
first_string = tab_strings[v]; // string 0, or the string with the first removed TI
tab_tis.push(first_string.match(/1[0-9]{9}/)); // analyze the string and get the new TI to put it in the table
var string_modif2 = first_string.replace(tab_tis[v], " "); // modify the string again to remove the new TI from the old string
tab_strings.push(string_modif2);
v += 1;
}
while(v < 15)
return tab_tis;
}