2

After reading this post and this doc, I'm trying to write a function that will return the index of each occurrence of a regular expression in a string (in this case, each occurrence of a number). I took this the code from the documentation linked above:

var myRe = /ab*/g;
var str = "abbcdefabh";
var myArray;
while ((myArray = myRe.exec(str)) != null)
{
  var msg = "Found " + myArray[0] + ".  ";
  msg += "Next match starts at " + myRe.lastIndex;
  print(msg);
}

And turned it into this:

var myRe = /([0-9]*)/g;
var str = "gfarg h43kjh arjh 343";
var myArray;

while ((myArray = myRe.exec(str)) != null)
{
  var msg = "Found " + myArray[0] + ".  ";
  msg += "Next match starts at " + myRe.lastIndex;
  alert(msg);
}

Which would loop infinitely showing the same result. I actually have two questions. How can I show the index of each whole number (which in my sample string "gfarg h43kjh arjh 343" would be 7 and 18). And, why is my current code looping infinitely?

Community
  • 1
  • 1
Juan
  • 15,274
  • 23
  • 105
  • 187

1 Answers1

2

Your code is looping infinitely because your regex matches the empty string. Don't do that :). Try:

var myRe = /([0-9]+)/g;

This will already find whole numbers. See http://jsfiddle.net/nrabinowitz/3aHxS/1/ for a working example.

nrabinowitz
  • 55,314
  • 10
  • 149
  • 165
  • OK Just a quick one, what if the regex (`myRe` above) is a parameter that my function will receive. How should I predict that it will loop forever and, say, throw an exception? Would it be by checking that the `index` property is 0 twice (which I assume means is not moving) or is there an easier way? – Juan Oct 25 '11 at 19:33
  • Well, as a safety measure, you could set a counter and check for `while ((myArray = myRe.exec(str)) != null && myCounter < maxIterations)`. Then if you wanted, you could throw an error inside the loop body if `myCounter == maxIterations`. – nrabinowitz Oct 25 '11 at 20:30
  • ...though if you just wanted to avoid this particular problem, I think you could test with `if (myRe.test(''))`, which would catch a regex that matched the empty string. – nrabinowitz Oct 25 '11 at 20:32