0

I need to parse JavaScript source code and match all regular expressions with the help of a regular expression :). First I tried this regular expression:

(?:\/.*\/)

But it does not work if the regular expression contains slash, like in the next source code

while (line.match(/[+*/]/))
        line = line.replace(/([+*/])\s(\d+)\s(\d+)/, function (s, op, a, b) {
            return operators[op](+a, +b);
        });

I don`t know how to keep all possibilities in one regular expression. Is there any way to match a regular expression in javascript source code using regular expressions?

  • 6
    Not a good idea. JavaScript syntax is way too complex. Use a full-blown parser to parse JS code, [such are freely available](http://esprima.org/) – Bergi Apr 14 '14 at 13:33
  • The reason your pattern didn't work is because `(?:)` means do not match. – Joe Habadas Apr 14 '14 at 13:43
  • @JoeHabadas: No. It means "match, but don't capture". Your regex matches exactly the same as his. – Tim Pietzcker Apr 14 '14 at 13:44
  • Well, that's what I meant, thanks for the clarification. – Joe Habadas Apr 14 '14 at 13:49
  • 1
    @TimPietzcker, what would I use to "capture, but don't match"? – Joe Habadas Apr 14 '14 at 15:47
  • @JoeHabadas: Very good question! You could use a capturing group within a lookahead assertion: `(?=(foo))` used on the string `"foo"` would have the match result `""`, and group 1 would contain `"foo"`. This is a contrived example, of course, but the feature itself is very useful, for example when looking for overlapping matches, as seen in [this answer](http://stackoverflow.com/questions/11326284/regex-is-it-possible-to-find-overlaping-groups/11326404#11326404). – Tim Pietzcker Apr 14 '14 at 15:50
  • @JoeHabadas: It's a normal positive lookahead assertion, yes, the only twist being that it also contains a capturing group. Nothing special really. – Tim Pietzcker Apr 14 '14 at 15:53

0 Answers0