Take the 2-minute tour ×

Does anyone know how to find regular expression string from javascript code? e.g. var pattern = /some regular expression/;

Is it possible to to with regular expression :) ?

share|improve this question
It is very unclear what your question is. Do you want to match a string with a regular expression? –  Mathias Schwarz Jul 5 '11 at 9:13
add comment

4 Answers

If I got your question right, and you need a regular expression which would find all the regular expressions in a JavaScript program, then I don't think it is possible. A regular expression in JavaScript does not have to use the // syntax, it can be defined as a string. Even a full-blown JavaScript parser would not be smart enough to detect a regular expression here, for instance:

var re = "abcde";
var regexClass = function() { return RegExp; }
var regex = new regexClass()(re);

So I would give up this idea unless you want to cover only a few very basic cases.

share|improve this answer
add comment

You want a regex to match a regex? Crazy. This might cover the simplest cases.

new RegExp("\/.+\/")

However, I peeked into the Javascript Textmate bundle and is has 2 regex for finding a regex start and end.

begin = '(?<=[=(:]|^|return)\s*(/)(?![/*+{}?])'
end   = '(/)[igm]*';

Which you could probably use as inspiration for toward your goal.

share|improve this answer
add comment

Thanks for answers I have found also that it is nearly impossible task to do, but here is my regex which parses source code just fine:

this.mainPattern = new RegExp(//single line comment
                           //multiline comment
                           //single or double quote strings
                           //regular expression literal in javascript code
                           "|([{]|[(]|[\[])|([}]|[)]|[\\]])", 'g');
share|improve this answer
add comment

Your Answer


