Regular expression to match JavaScript function
I know this question is 5 years old, but contrary to what everyone else has said, i have actually concocted a quite effective pattern for doing as you have asked. Albeit, quite complex, I have used this several times in my own projects and I've yet to have a hiccup... wish I had seen this question much sooner. Hope this helps (If not for you, hopefully for those who are searching for a similar solution)
function\s*([A-z0-9]+)?\s*\((?:[^)(]+|\((?:[^)(]+|\([^)(]*\))*\))*\)\s*\{(?:[^}{]+|\{(?:[^}{]+|\{[^}{]*\})*\})*\}
Are you trying to parse JS with regex? If so, DON'T. Regex is a VERY BAD parser see these questions as well.
When should I use a parser?
RegEx match open tags except XHTML self-contained tags
If you're not supposed to use Regular Expressions to parse HTML, then how are HTML parsers written?
In JS, a function can contain functions (which in turn can contain functions, and so on):
x = function() {
this.y = function() { /* ... */ };
function z() { /* ... */ }
};
Also, you can have string literals or comments that can contain (sub) strings that either look like functions:
var s = "function notAFunction(){}";
/*
function alsoNotAFunction(){}
*/
or contain parts of functions your regex would trip over:
function f() {
var s = "not a closing bracket: } ";
}
So, to answer you question what the regex would be to match functions in JS: it does not exist. You should/could use a proper parser for this.