Javascript - Regexp Exec Internal Index Doesn't Progress If First Char Is Not A Match
I need to match numbers that are not preceeded by '/' in a group. In order to do this I made the following regex: var reg = /(^|[^,\/])([0-9]*\.?[0-9]*)/g; First part matches star
Solution 1:
Infinite loop is caused by the fact your regex can match an empty string. You are not likely to need empty strings (even judging by your code), so make it match at least one digit, replace the last *
with +
:
var reg = /(^|[^,\/])([0-9]*\.?[0-9]+)/g;
var text = "a 1 b a 2 ana 1/2 are mere (55";
var numbers=[];
while (match = reg.exec(text)) {
numbers.push({'index': match.index + match[1].length, 'value': match[2]});
}
console.log(numbers);
Note that this regex will not match numbers like 34.
and in that case you may use /(^|[^,\/])([0-9]*\.?[0-9]+|[0-9]*\.)/g
, see this regex demo.
Alternatively, you may use another "trick", advance the regex lastIndex
manually upon no match:
var reg = /(^|[^,\/])([0-9]*\.?[0-9]+)/g;
var text = "a 1 b a 2 ana 1/2 are mere (55";
var numbers=[];
while (match = reg.exec(text)) {
if (match.index === reg.lastIndex) {
reg.lastIndex++;
}
if (match[2]) numbers.push({'index': match.index + match[1].length, 'value': match[2]});
}
console.log(numbers);
Post a Comment for "Javascript - Regexp Exec Internal Index Doesn't Progress If First Char Is Not A Match"