Reputation: 1184
I want to be able to extract all numbers (including floating point) from a string in JavaScript.
"-5. -2 3.1415 test 2.4".match(...)
returns
["-2", "3.1415", "2.4"]
So far I have /[-+]?(\d*\.?\d+)/g
, but this seems to return 5
along with the other numbers. I want to avoid that since in the string the "word" is 5. and not 5 or 5.0. Any hints?
Upvotes: 3
Views: 3888
Reputation: 5822
The reason this question is difficult to answer is you need to be able to check that the character before the number or before the + or - is either a whitespace or the start of the line.
As JavaScript does not have the ability to lookbehind a solution for this by using the .match()
method on a string becomes nearly impossible. In light of this here is my solution.
var extractNumbers = (function ( ) {
numRegexs = [
/( |^)([+-]?[0-9]+)( |$)/g,
/( |^)([+-]?[0-9]+\.[0-9]+)( |$)/g,
/( |^)([+-]?[0-9]+\.[0-9]+([eE][+-])?[0-9]+)( |$)/g
];
return function( str ) {
var results = [], temp;
for( var i = 0, len = numRegexs.length; i < len; i++ ) {
while( temp = numRegexs[i].exec( str ) ) {
results.push( temp[2] );
}
}
return results;
}
}( ));
The regular expressions in the numRegexs array correspond to integers, floats and exponential numbers.
Demo here
Upvotes: 1
Reputation: 4592
Given that your example string has spaces between the items, I would rather do:
var tokens = "-5. -2 3.1415 test 2.4".split(" ");
var numbers = [];
for( var i = 0 ; i < tokens.length ; i++ )
if( isNumber( tokens[i]) )
numbers.push( tokens[i]*1 );
//numbers array should have all numbers
//Borrowed this function from here:
//http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric
function isNumber(n) {
return !isNaN(parseFloat(n*1)) && isFinite(n*1) && !endsWith(n,".");
}
endsWith = function( s , suffix ) {
return s.indexOf(suffix, s.length - suffix.length) !== -1;
};
Upvotes: 0
Reputation: 349232
If you want to not include the dot, a look-ahead would make sense:
/[-+]?\d*(\.(?=\d))?\d+/g
Another option is to move the second \d+
inside the parentheses:
/[-+]?\d+(\.\d+)?/g
Upvotes: 2
Reputation: 104840
This rx gets numbers represented in strings, with or without signs, decimals or exponential format-
rx=/[+-]?((.\d+)|(\d+(.\d+)?)([eE][+-]?\d+)?)/g
String.prototype.getNums= function(){
var rx=/[+-]?((\.\d+)|(\d+(\.\d+)?)([eE][+-]?\d+)?)/g,
mapN= this.match(rx) || [];
return mapN.map(Number);
};
var s= 'When it is -40 degrees outside, it doesn\'t matter that '+
'7 roses cost $14.35 and 7 submarines cost $1.435e+9.';
s.getNums();
/* returned value: (Array) -40, 7, 14.35, 7, 1435000000 */
Upvotes: 1