Reputation: 41605
I'm trying to get the functions from an input string by using regular expressions.
So far, I managed to get the JavaScript kind of function declarations with the following regex:
/(\b(f|F)unction(.*?)\((.*?)\)\s*\{)/g
Which when applied like this, will return me whole declaration on the first index:
var re = /(\b(f|F)unction(.*?)\((.*?)\)\s*\{)/g;
while ((m = re.exec(text)) !== null) {
//m[0] contains the function declaration
declarations.push(m[0]);
}
Now, I would like to get in the returned match, the whole content of each of the functions so I can work with it later on (removed it, wrap it...)
I haven't managed to find a regext to do so, so far, I got this:
(\b(f|F)unction(.*?)\((.*?)\)\s*\{)(.*?|\n)*\}
But of course, it catches the first closing bracket }
instead of the one at the end of each of the functions.
Any idea of how to get the closing }
of each function?
Upvotes: 0
Views: 93
Reputation: 109080
Any idea of how to get the closing } of each function?
This will be very hard with a regex. Because the function body can include any number of possibly nested brace pairs. And then consider strings containing unmatched braces in the function body.
To parse a non-regular language you need something more powerful than regular expressions: a parser for that language.
(Some regex variants have some ability to matched paired characters, but firstly JavaScript's regex engine isn't one; and secondly then there are those strings….)
Upvotes: 4