regular expression to extract fraction, decimal and number from a string [closed] - javascript

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I need a regex to extract fraction, decimal and integer values from a given string. For example, an input will be like following.
1/2 apples
1.5 orange
2.5 orange
1 lemon
And output should be following.
1/2
1.5
2.5
1
I figured out how to extract fraction, decimal and integer values separately using 3 different regex, but I can't figure out a way to extract all the possible number values with one regex.
I'm currently using Javascript String object's match method.
Any help will be appreciated.

Use regex pattern
\d+([/.]\d+)?
...which leads to Javascript code
var n = str.match(/\d+([\/.]\d+)?/g);
Check this fiddle/demo.

Then why not present your working regexes?
But here is how, simply use an alternation:
\d+(\/\d+|\.\d+)?
This is already slightly optimized. You could simply separate your three regexes by |.

The easiest possible regular expression in this case (assuming that your numbers always in the beginning of the string) is:
^\S+
Examples:
'1/2 apples'.match(/^\S+/) // ["1/2"]
'1 lemon'.match(/^\S+/) // ["1"]

If you are sure that all strings have the same format (i.e. starts with amount, then space, then text), there is even no need in regular expression:
"1/2 apples".split(" ").shift(); // gives "1/2"

Related

How to handle floating points in a JavaScript calculator?

Why is this not a duplicate of these great SO articles?
While the two posts linked in the comments below are excellent I am specifically looking for information that helps me to address this issue in native JS. I know that JS shouldn't be the first choice for complex math, but given the limitation that this calculator is meant to run in the browser it is the tool that I have decided to work with.
Background
I'm trying to make a calculator with TypeScript without any libraries (like Big.js) and without using string concatenation in the inner logic of the calculator.
Examples
When a user wants to type the number 8.5:
The 8 key is pressed
The decimal key is pressed
The 5 key is pressed
Mathematically I create this number in the display with the following snippet:
8 + 5 * 0.1
This works but if I continue down the decimal places I encounter something unexpected:
8.5 + 5 * 0.01 // 8.55
8.55 + 5 * 0.001 // 8.555000000000001
Question
What is the best way to handle this without converting the number to a string? Is there an intelligent way to impose a limit on the precision of the calculator so that it only supports accuracy to so many decimal places?
Thanks for your help!
Use .toFixed():
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed
or .toPrecision():
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toPrecision
depending on your needs.
Note that you don't need to convert numbers all the time. The only place to convert - is for the final output to the view. In this case we can even leave it in string format.
That is an answer to the question "how to get manage with" (like in description). About "why do we get such result" - first comment provides great answer.
The easiest way to get the Number value that is closest to what the user enters is to build a numeral in a string from the user’s keypress and then convert them with String.toNumber().
Numbers such as 8.55 or 8.555 are not exactly representable in the Number format. The closest values are 8.550000000000000710542735760100185871124267578125 and 8.55499999999999971578290569595992565155029296875. Converting the strings “8.55” and “8.555” with .toNumber() should produce these values.
Because these are the closest representable values, no calculation or algorithm can produce any closer values in the Number format.
For simple additions, subtractions, and limited multiplications, you can mimic decimal arithmetic by rounding to a desired number of decimal digits after each Number operation. However, this is generally not a feasible approach because other operations and various sequences of operations will exceed the ability to mimic decimal arithmetic reasonably.

Issue working with numbers in Javascript [duplicate]

This question already has answers here:
Large numbers erroneously rounded in JavaScript
(6 answers)
Closed 5 years ago.
I'm new in developing javascript apps, i have a doubt about a behaviour that i'm going to try to explain.
If i execute:
Number(5555555555555555);
Result: 5555555555555555
But if i execute:
Number(55555555555555555);
Result: 55555555555555550
Anybody can explain to me what is the reason of this? Thanks!!
If you need to work with such big numbers I would suggest you use some of the big integer libraries such as this. The reason this happens as far as I know is the way processors and memory work. It's no related to some "bug" in JS.
Integers (numbers without a period or exponent notation) are accurate up to 15 digits. Javacript simply adds zeros to keep the number accurate in terms of its digit length.
Documentation

explanation of regex rule [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I've inherited some code which validates a coupon.
The logic of this coupon is a regular expression rule verified with JS.
I don't have much experience with this, and will really appreciate if someone can help me understand it.
This is the rule:
theStr.match('^[a-z]{1}[0-9]{3}[a-z]{1}$')
Must start with a lowercase letter followed by three numbers and another lowercase letter. Also note that in JS you use /regex/ not 'regex'.
This site can be very helpful for explaining regexes: http://regex101.com/
In this case, that regex matches the following, in this order:
beginning of a string/line
any lower case letter
repeated only once (no repetitions)
any digit
repeated exactly 3 times
any lower case letter
repeated only once
end of string/line
This would match a string like "b589n".
Line starts with one lowercase letter a-z, followed by three digits, and ending with one lowercase letter a-z
The ^ symbol means "at the start of the line", the $ symbol means "at the end of the line", the stuff in the []'s is the chars to match on, and the number in the {}'s is the number of times to repeat.

How Can decode sha1 code? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have a code but i can't decode it so i need help for you. Please help me.
Firstly I don't know it type. What is it ? sha1 ? md5 ? hash ? i know just this code have 40 character.
How can decode this security code ? it's have game score so i need decode it but i can't decode it.
This code: "security":"c6aefe7f8c9fd439f59635efc82fcbd4f6cd4b9c"
it's protect game inform. When I changed anything, it's not confirm security code.
Full Code: {"security":"c6aefe7f8c9fd439f59635efc82fcbd4f6cd4b9c","time":40844,"numberOfBirdsShot":2,"type":"LevelComplete","blocks":"800,100,130,130,130,130,310,110,300,300,110,10,150,70,120,60,40,60,60,110,130,80,70,140,180,20,190,20,40,40,90,70,10,10,40,10,40,190,190,40,40,50,20,130,20,140,10,60,90,120,120,10,10,80,100,120,30,90,90,290,100,80,120,70,70,370,150,50,50,160,160,10,30,250,160,180,180,130,70,70,130,60,30,30,130,320,70,70,170,70,150,40,40,90,30,110,120,270,60,40,180,140,220,30,20,160,460,10,30,70,110,350,290,700,550,90,100,90,10,100,40,40,80,40,40,170,80,80,70,70,70,120,170,10,20,50,10,10,40,70,70,50,20,80,80,20,20,90,220,220,230,50,20,20,80,60,30,30,280,90,50,260,80,120,80,80,50,110,90,20,20,30,30,60,70,40,40,10,30,110,100,50,40,50,100,90,20,20,30,160,10,10,20,10,10,90,70,30,210,180,90,80,80,40,160,60,30,80,80,80,0,500,5000,500,500,500,500,5000,500,500,500,500,500,500,500,500,500,500,500,5000,500,500,5000,500,500,500,500,500,500,0,10000,10000","sessionID":"2DAB169CF4F766CC69CA2C5A02339CB7.f119dcaaa5c087f52aa2ad687312f9f46d402972","levelID":"1-1","score":73150,"gameplay":"WIN1-1##2#321:16.489984194253722:-25.291503791549072:1:-161.45947702629903#505:16.306849998012037:-27.166930977940375:1:172.61390103177405##2#333#517##0","userLevelID":"0c4679cd-5fb0-441e-a257-a060010bdb3d","userID":"1a7c1755-a7e7-48a0-9e7d-a04a0142a595"}
You can't decode a sha1 hash.
A cryptographically strong hash function exhibits two features: it is irreversible and it minimizes collisions. Irreversibility means that the original data cannot be reconstructed from its hash. Cf. encryption, which must be reversible (see write-only memory.) A collision occurs when two different sets of data generate the same hash.
If it has 40 characters of hex, then that's 20 bytes or 160 bits which would suggest it's SHA-1.
It's not possible (in a reasonable amount of time). What you can do is check rainbowtables or try to find hash collisions.

Translate this JavaScript Gibberish please? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I'm trying to modify and update an old Greasemonkey script with the goal of automatically adding an affiliate ID to all Amazon links. I'm a novice when it comes to JavaScript, but I'm usually pretty good about modifying existing scripts in any language. There's just one line here that I can't wrap my head around.
The script I started with is outdated, so I don't know if there is a problem with the syntax or if the link format has changed. Can somebody please help me understand what this line is doing so I can make changes to it?
const affiliateLink = /(obidos.(ASIN.{12}([^\/]*(=|%3D)[^\/]*\/)*|redirect[^\/]*.(tag=)?))[^\/&]+/i;
Alright, you asked for it :)
Start the regular expression:
/
Start a group operation:
(
Search for the text "obidos" followed by any single character
obidos.
Open another group operator:
(
Search for the text "ASIN" followed by any 12 characters
ASIN.{12}
Another group operation:
(
Followed by 0 or more characters that are not slashes:
[^\/]*
Group operation searching for an '=' character or a url encoded '=' (%3D):
(=|%3D)
Followed by 0 or more characters that are not slashes:
[^\/]*
Followed by slash (and closes the current group), which can be repeated 0 or more times:
\/)*
Allows the pattern to match if the previous group was found OR everything to the right of the bar is matched:
|
Matches the text "redirect" followed by 0 or more chatacters that are not a slash:
redirect[^\/]*
Matches any single character, followed optionally by the text "tag=":
.(tag=)?
Closes the two group operations we're currently still inside of:
))
Followed by one or more characters that are not a slash or &:
[^\/&]+
Closes the regular expression:
/
Download a copy of expresso, its a great utility for this and comes in handy for all this stuff. then just place the regex into that (everything between the starting slashes and ending slash).
I would describe what string it matches e.c.t. but its fairly complex as theres lots of components to it. Its easier for you to look at it yourself. expresso provides a more english explanation of each pattern

Categories

Resources