Regex Loops Continuously Without Terminating To Find A Match
Solution 1:
According to the documentation,
JavaScript RegExp objects are stateful when they have the global or sticky flags set (e.g.
/foo/gor/foo/y). They store alastIndexfrom the previous match....
If the match succeeds, the exec() method returns an array and updates the
lastIndexproperty of the regular expression object.
Now imagine what happens on the first iteration. The regex finds a zero width match at index 0, so it sets the lastIndex to 0. Then on the second iteration, it starts searching from 0, where it finds another zero-width match, so it sets lastIndex to 0 again. And the cycle continues.
Therefore, you should put an if statement there to check if the match is zero-width. If it is, increment the last index, so that it doesn't give you the same match again.
functionmyFunction() {
var ptrn = newRegExp("u?", "gim");
var match;
var i = 0;
while ((match = ptrn.exec("color colour")) != null) {
console.log(JSON.stringify(match));
if (match.index == ptrn.lastIndex) {
ptrn.lastIndex++;
}
}
}
myFunction()Solution 2:
? means "zero or one". u? means "match on a single instance of u or a single instance of nothing." So, it's not surprising that u? matches your string infinitely many times. I guess I wouldn't have predicted that, but it's not alarming.
When you change your regex to ou?, that means "require an o, optionally followed by a u". It does not mean "find zero or one ou combination." There are two os in your string, which means it will match twice.
Post a Comment for "Regex Loops Continuously Without Terminating To Find A Match"