I have the use case, where I need to allow for processing an arbitrary array of strings, by an arbitrary regex, which is created either by a regex literal, or through the new RegExp()
constructor.
It all works fine, until the global g
flag is used with capturing groups.
I read a few answers on SO, and the proposed solution is to use regex.exec(string) in a while loop, e.g. How do you access the matched groups in a JavaScript regular expression?, JavaScript regular expressions and sub-matches
I also talked about it on IRC, and was advised against the implementation all together:
but there's regexes that will segfault your engine, unless you're using spidermonkey.
So here is a corner case, try pasting it into a fiddle or plunker, or even the console, it just breaks:
var regexString = '([^-]*)';
var flags = 'ig';
var regex = new RegExp(regexString, flags);
var arr = ['some-property-image.png', 'another-prop-video.png', 'y-no-work.bmp'];
var result = [];
arr.forEach(function(item) {
var match;
var inter = [];
while (match = regex.exec(item)) {
inter.push(match[0]);
}
});
console.log(result);
I did tried it on regex101.com https://regex101.com/r/xG0cL4/1
It breaks even if I do it without the quantifier, i.e. /([^-])/g
https://regex101.com/r/yT7sQ2/1
My question: what is the (correct|safe)
way to process arbitrary regexes against arbitrary strings?