0

This regex in JavaScript is returning only the first real number from a given string, where I expect an array of two, as I am using /g. Where is my mistake?

/[-+]?[0-9]*\.?[0-9]+/g.exec("-8.075090 -35.893450( descr)")

returns:

["-8.075090"]
piet.t
  • 11,718
  • 21
  • 43
  • 52
gradusas
  • 53
  • 1
  • 7

2 Answers2

2

Try this code:

var input = "-8.075090 -35.893450( descr)";
var ptrn = /[-+]?[0-9]*\.?[0-9]+/g;
var match;
while ((match = ptrn.exec(input)) != null) {
    alert(match);
}

Demo

http://jsfiddle.net/kCm4z/

Discussion

The exec method only returns the first match. It must be called repeatedly until it returns null for gettting all matches.

Alternatively, the regex can be written like this:

/[-+]?\d*\.?\d+/g
Stephan
  • 41,764
  • 65
  • 238
  • 329
1

String.prototype.match gives you all matches:

var r = /[-+]?[0-9]*\.?[0-9]+/g
var s = "-8.075090 -35.893450( descr)"

console.log(s.match(r))
//=> ["-8.075090", "-35.893450"]
DMKE
  • 4,553
  • 1
  • 31
  • 50
  • Super. Alex answered why `exec` method did not work for me. But for practical purposes `String.match` is what I need in my case. – gradusas Feb 13 '14 at 10:33