Regular Expression In Javascript For Negative Floating Point Number Result Stored In Array
Solution 1:
This should do :
[-+]?([0-9]*\.[0-9]+|[0-9]+)
And test the regex for JS here at : http://www.regular-expressions.info/javascriptexample.html
Paste your regexp
and click on show match
.
Also, look at this link for more info : FLOATING POINT REGEX
Solution 2:
I don't understand exactly your question
Is it that you want to have the same value as a result on array[0]
and array[1]
? It's pointless to do so; also you can just write some code to do it for you, instead of forcing regexp to do so.
But it's possible - you can just hide groups by putting ?:
at the beginning of it or just skip them if they are not needed. You can create additional groups by just adding more parentheses. So your regexp modified will look like this:
input.match(/^([-+]?\d*\.?\d*)$/)
It makes no sense though
Solution 3:
A better regular expression would be:
/-?\d+(?:.\d+)?/
It matches sequences of at least 1 digits that may start with a -
sign and may be broken up by a .
Your original regular expression also states that this is the entire string (because you add the ^ and $ signs to it). If you want to extract the numbers from a longer text, you shouldn't do that.
Once you have extracted the number (you have the string representation of a floating point), you can use the unary plus operator to convert it to a Number. After that simply create an array with the number twice and you're done.
var input = '123.45';
varnumber = +input;
var arr = [number, number];
NOTE: as fara as i know, the plus before the floating point doesn't actually belong to the number, so you shouldn't match it. +123.45
is not a valid floating point. Feel free to change the start to [+-]?
instead of -?
if you consider it valid.
Some other examples of floating points i don't consider valid:
+123
.123
-.123
123.
EDIT: Working JsBin: http://jsbin.com/ehurAva/1/edit
Post a Comment for "Regular Expression In Javascript For Negative Floating Point Number Result Stored In Array"