0

I have strings like this:

"1 -2 -0.00529366960223319 -1.72662226752857E-5 some text"

And I want to parse the numbers to an array, removing text, using javascript, to return this:

[1, -2, -0.00529366960223319, -1.72662226752857E-5]

I tried lots of expression, like the following:

/[-+]?[0-9]*.?[0-9]+([eE][-+]?[0-9]+)?/

without success, any help?

thanks in advance!

Marcelo Abiarraj
  • 199
  • 3
  • 18

2 Answers2

4

You don't need regex for this:

function isNumeric(n) {  /* http://stackoverflow.com/a/1830844/1529630 */
  return !isNaN(parseFloat(n)) && isFinite(n);
}
var str = "1 -2 -0.00529366960223319 -1.72662226752857E-5 some text",
    arr = str.split(" ").filter(isNumeric).map(Number);
Oriol
  • 274,082
  • 63
  • 437
  • 513
  • `!isNaN(n)` is sufficient, no reason to bring `parseFloat` into the equation when it casts differently than `Number` would. – zzzzBov Mar 02 '16 at 18:17
  • @zzzzBov But e.g. `!isNaN('\t') === true`, so `parseFloat` is needed. Or maybe I could split with `/\s+/` to remove these cases. – Oriol Mar 02 '16 at 18:20
  • `Number('\t') === 0`, which is a number. – zzzzBov Mar 02 '16 at 18:24
0

You can use this regex: /[-+]?\d*\.?\d+([eE][-+]?\d+)?/g

You was almost there.
Remember to escape all the special signs like . if you literally want it, or it will match with any character.
The g at end of regex enable the global matches.

var src = "+1 -2 -0.00529366960223319 -1.72662226752857E-5 some text 25e46";

var reg = /[-+]?\d*\.?\d+([eE][-+]?\d+)?/g;

res = src.match(reg);

// The matches are in elements 0 through n.
for (var i = 0; i < res.length; i++) {
    document.body.innerHTML += "submatch " + i + ": " +  res[i] + "<br/>";
}