How do I extract the numbers out of a string like this:
$1.50
Everything but the currency symbol. Or from something like this:
rofl1.50lmao
Just asking if there's an existing function that I'm not a aware of.
There is no builtin function in AS3 for that. A simple RegExp like this one should help you :
/[0-9]+.?[0-9]*/
This is an example, and should be refactored depending your context.
Here is a more precise RegEx from Gunslinger47:
/-?\d*\.?\d+([eE]\d+)?/
This is "plain" JavaScript, but FWIW:
justNumsAndDots = "rofl1.50lmao".replace(/[^\d.]/g,"") // -> "1.50" (string)
asIntegral = parseInt("0" + justNumsAndDots, 10) // -> 1 (number)
asNumber = parseFloat("0" + justNumsAndDots) // -> 1.5 (number)
asTwoDecimalPlaces = (2 + asNumber).toFixed(2) // -> "3.50" (string)
Notes:
Doesn't take localization into account.
Radix (base-10) is passed to parseInt to avoid potential octal conversion (not sure if this "issue" plagues AS).
"0" is added to the start of justNumsAndDots so parseInt/parseFloat will never return a NaN here. (e.g. parseFloat(".") -> NaN, parseFloat("0.") -> 0). If NaN's are desired, alter to suite.
Input like "rofl1.chopter50lolz" will be stripped to "1.50", it might be over-greedy, depending.
Adapt to AS as necessary.
Happy coding.
As far as I know, no. You can parse every character against an array of valid characters, or use regexp.
Related
I have a specific problem that I got some issues figuring out. I want to create an operator in Ada that can divide a float value with a character and then return as an integer.
I understand that the operator should be a function with "/" and some kind of type conversion from float value and a character to an integer. But how would the return value look like and which rounding of the float value would be appropriate?
update.
Let's say I would like to put in the float value -21.8 and the character '2'. The answer should be -11. I created a subprogram for this but I feel like the solution could be something more simple.
function "/"(Float_Val : in Float;
Ch : in Character) return integer is
begin
if Float_Val < Float(0) then return
(Integer(Float'Rounding(Float_Val)) - (Character'Pos(Ch) - (Character'Pos('0'))) + 1) / (Character'Pos(Ch) - (Character'Pos('0')));
else return
(Integer(Float'Rounding(Float_Val)) + (Character'Pos(Ch) - (Character'Pos('0'))) - 1) / (Character'Pos(Ch) - (Character'Pos('0')));
end if;
end "/";
and "/" is called in my main program by
Put(Float_Val / Ch, Width => 0);
I wouldn’t want to call this weird function "/", but if you must ... the skeleton body would be
function "/" (L : Float; R : Character) return Integer is
begin
-- this is where the magic happens
end "/";
I don’t see why you’d need to round L.
Without a bit more explanation as to what algorithm you want to use, that’s all I can say.
Update:
This seems to work quite well:
function "/" (L : Float; R : Character) return Integer
with Pre => R in '1' .. '9'
is
begin
return Integer (L) / (Character'Pos (R) - Character'Pos ('0'));
end "/";
See ARM 4.6(33).
To answer your question about rounding, and to fill in the "magic" in Simon's answer, you must explain better what you want to compute. For example, what should the result of 4.567 / "A" be? And what would do you do to compute it by hand?
Sounds to me like you want to translate something from a poor type language to the rich type language Ada.
If you like to do this the Ada way it will require some reverse engineering to find out what the types ‘integer‘, ‘float’, and ‘character‘ really means. Then I guess an explaining name for ‘/‘ will emerge.
i have extracted the fix message as below from Unix server and now need to convert this message into JSON. how can we do this?
8=FIXT.1.1|9=449|11=ABCD1|35=AE|34=1734|49=REPOFIXUAT|52=20140402-11:38:34|56=TR_UAT_VENDOR|1128=8|15=GBP|31=1.7666|32=50000000.00|55=GBP/USD|60=20140402-11:07:33|63=B|64=20140415|65=OR|75=20140402|150=F|167=FOR|194=1.7654|195=0.0012|460=4|571=7852455|1003=2 USD|1056=88330000.00|1057=N|552=1|54=2|37=20140402-12:36:48|11=NOREF|453=4|448=ZERO|447=D|452=3|448=MBY2|447=D|452=1|448=LMEB|447=D|452=16|448=DOR|447=D|452=11|826=0|78=1|79=default|80=50000000.00|5967=88330000.00|10=111
Note: I tried to make this a comment on the answer provided by #selbie, but the text was too long for a comment, so I am making it an answer.
#selbie's answer will work most of the time, but there are two edge cases in which it could fail.
First, in a tag=value field where the value is of type STRING, it is legal for value to contain the = character. To correctly cope with this possibility, the Java statement:
pair = item.split("=");
should be changed to:
pair = item.split("=", 2);
The second edge case is when there are a pair of fields, the first of which is of type LENGTH and the second is of type DATA. In this case, the value of the LENGTH fields specifies the length of the DATA field (without the delimiter), and it is legal for the value of the DATA field to contain the delimiter character (ASCII character 1, but denoted as | in both the question and Selbie's answer). Selbie's code cannot be modified in a trivial manner to deal with this edge case. Instead, you will need a more complex algorithm that consults a FIX data dictionary to determine the type of each field.
Since you didn't tag your question for any particular programming language, I'll give you a few sample solutions:
In javascript:
let s = "8=FIXT.1.1|9=449|11=ABCD1|35=AE|34=1734|49=REPOFIXUAT|52=20140402-11:38:34|56=TR_UAT_VENDOR|1128=8|15=GBP|31=1.7666|32=50000000.00|55=GBP/USD|60=20140402-11:07:33|63=B|64=20140415|65=OR|75=20140402|150=F|167=FOR|194=1.7654|195=0.0012|460=4|571=7852455|1003=2 USD|1056=88330000.00|1057=N|552=1|54=2|37=20140402-12:36:48|11=NOREF|453=4|448=ZERO|447=D|452=3|448=MBY2|447=D|452=1|448=LMEB|447=D|452=16|448=DOR|447=D|452=11|826=0|78=1|79=default|80=50000000.00|5967=88330000.00|10=111"
let obj = {};
items = s.split("|")
items.forEach(item=>{
let pair = item.split("=");
obj[pair[0]] = pair[1];
});
let jsonString = JSON.stringify(obj);
Python:
import json
s = "8=FIXT.1.1|9=449|11=ABCD1|35=AE|34=1734|49=REPOFIXUAT|52=20140402-11:38:34|56=TR_UAT_VENDOR|1128=8|15=GBP|31=1.7666|32=50000000.00|55=GBP/USD|60=20140402-11:07:33|63=B|64=20140415|65=OR|75=20140402|150=F|167=FOR|194=1.7654|195=0.0012|460=4|571=7852455|1003=2 USD|1056=88330000.00|1057=N|552=1|54=2|37=20140402-12:36:48|11=NOREF|453=4|448=ZERO|447=D|452=3|448=MBY2|447=D|452=1|448=LMEB|447=D|452=16|448=DOR|447=D|452=11|826=0|78=1|79=default|80=50000000.00|5967=88330000.00|10=111"
obj = {}
for item in s.split("|"):
pair = item.split("=")
obj[pair[0]] = pair[1]
jsonString = json.dumps(obj)
Porting the above solutions to other languages is an exercise for yourself. There's comments below about semantic ordering and handling cases where the the = or | chars are part of the content. That's on you to explore if you need to support those scenarios.
I have some similar register definition, and I want to write under the regmap construct.
My code currently looks like this:
val regs = RegInit(Vec(Seq.fill(5)(0.U(32.W))))
regmap (
...
0x30 -> Seq(RegField(32,regs(0),RegFieldDesc("reg0",""),
0x34 -> Seq(RegField(32,regs(1),RegFieldDesc("reg1",""),
0x38 -> Seq(RegField(32,regs(2),RegFieldDesc("reg2",""),
0x3C -> Seq(RegField(32,regs(3),RegFieldDesc("reg3",""),
0x40 -> Seq(RegField(32,regs(4),RegFieldDesc("reg4",""),
...
)
My question, is there a way to write the above in more concise way using one of the Scala Iterators?
Another requirement I have is that I still need to be able to add register before and after this iterator (3 dots lines).
I believe ,using iterators is good against copy/paste mistakes and looks better.
Thanks in advance for any help.
I think the pattern for this would probably be something like
val regs = RegInit(Vec(Seq.fill(5)(0.U(32.W))))
val tuples = regs.zipWithIndex.map { case (reg, i) =>
(0x30 + (i * 4)) -> Seq(RegField(32,regs,RegFieldDesc(s"reg$i","")))
}
regmap(tuples :_*)
The only bit of magic there is the :_* which converts a sequence into a list of parameters.You don't need the multiple steps that I used either, I just wanted to make it easy to see what is going on.
I have the next piece of code:
internal static string GetNetBiosDomainFromMember(string memberName)
{
int indexOf = memberName.IndexOf("DC=", StringComparison.InvariantCultureIgnoreCase);
indexOf += "DC=".Length;
string domaninName = memberName.Substring(indexOf, memberName.Length - indexOf);
if (domaninName.Contains(","))
{
domaninName = domaninName.Split(new[] { "," }, StringSplitOptions.None)[0];
}
return domaninName;
}
I am making some parsings for AD, so I have some strings like "DC=", "objectCategory=", "LDAP://", ",", "." so and so.
I found the above code more readable than the code below:(You may found the opposed, let' me know.)
private const string DcString = "DC=";
private const string Comma = ",";
internal static string GetNetBiosDomainFromMember(string memberName)
{
int indexOf = memberName.IndexOf(DcString, StringComparison.InvariantCultureIgnoreCase);
indexOf += DcString.Length;
string domaninName = memberName.Substring(indexOf, memberName.Length - indexOf);
if (domaninName.Contains(CommaString))
{
domaninName = domaninName.Split(new[] { CommaString }, StringSplitOptions.None)[0];
}
return domaninName;
}
Even I may have "DC" and "DC=", I should think in the names for this variables or divide these in two :(. Then my question:
Should I avoid magic strings as possible?
UPDATED.
Some conclusions:
There are ways to avoid using strings at all, which might be better. To achieve it could be used: static classes, enumerators, numeric constants, IOC containers and even reflection.
A constant string help you to ensure you don't have any typos (in all references to a string).
Constant strings for punctuation don't have any global semantic. Would be more readable to use these as they are ",". Use a constant for this case may be considered if that constant may change in the future, like change "," by "." (Have a constant may help you in that refactoring although modern tools as resharper do this without need of a constant or variable).
If you only use it string once you do not need to make it into a constant. Consider however that a constant can be documented and shows up in documentation (as Javadocs). This may be important for non-trivial string values.
I would certainly make constants for the actual names like "DC" and "objectCategory", but not for the punctuation. The point of this is to make sure you don't have any typos and such and that you can easily find all of the references for the places that use that magic string. The punctuation is not really part of that.
Just to be clear, I'm assuming the magic strings are things that you have to deal with, that you don't have the option of making them a number defined by a constant. As in the comment to your question, that's always preferable if that's possible. But sometimes you must use a string if you have to interface with some other system that requires it.
Is there a way to test a string, such as the one below to see if it's an actual number value?
var theStr:String = '05';
I want to differentiate between the string value above and one such as this:
var theStr2:String = 'asdfl';
Thanks!
Yes use isNaN function to test if it the String is a valid Number:
var n:Number=Number(theStr);
if (isNaN(n)){
trace("not a number");
} else {
trace("number="+n);
}
You must cast to Number to get is NaN. If you use int letters can be cast to 0.
If you are just interested in checking integers you could use the match function as follows, the regex for numbers is more complicated and you would likely be better off following the casting method Patrick provided.
if (s.match(/^\d+$/)){//do something}
Of course if you are going to need to cast it anyway then using isNaN makes perfect sense. Just thought I'd offer an alternative in case you weren't going to cast it.
This code will return true if s contains only digits (no spaces, decimals, letters etc...) and requires there be at least 1 digit.