You will not get away with this using a single regex. You've now stumbled upon a single corner case which your regex doesn't handler properly, but there are many, many more. Your regex will break when there's an opening regexp literal inside a multi- or single-line comment, or when a /
occurs inside a string literal.
The only when to reliably solve this would be to parse the JavaScript, and inspect the token stream the parser (or lexer) produces.
To get started, see: JavaScript parser in JavaScript
user3371384 wrote:
I don't care about comments, because I remove them before getting regexp literals, same about strings.
Regardless, there are more corner cases:
var e = 8, f = 4, g = 2;
// ...
var x = e/f/g; // your regex will match `/f/g` as a regex literal
user3371384 wrote:
In many code parsers the same algorythm is used: find slash, then find next slash (if no backslash before it), all chars inside is regexp.
That may well be, but that is a very inaccurate algorithm (as you can see by the counter example I gave above). There's also the shorthand /=
that might foul up the regex.
Anyway, you seem to have made up your mind about using a regex for this...
You placed the .
in the wrong place: you only want to match any char after the backslash. Try this:
/\/([^\/]|\\.)+\/[gmi]*/gi