0

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 :) ?

1
  • 7
    It is very unclear what your question is. Do you want to match a string with a regular expression? Commented Jul 5, 2011 at 9:13

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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
                           "|(?:(?:[/].+[/])[img]?[\\s]?(?=[;]|[,]|[)]))"+
                           //brackets
                           "|([{]|[(]|[\[])|([}]|[)]|[\\]])", 'g');

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.