Regular Expressions for matching functions in javascript source code?

javascript, regex

Solution

There are a certain things that regular expressions just aren't very good at. That doesn't mean it's impossible to build an expression that will work, just that it's probably not a good fit. Among those things:

- multi-line input

- nesting

Javascript function blocks tend to cover multiple lines, and you are going to want to find the matching "{" and "}" braces that signify the start and end of the block, which could be nested to an unknown depth. You also need to account for potential braces used inside comments. RegEx will be painful for this.

That doesn't mean it's impossible, though. You might have additional information about the nature of the functions you're looking for. If you can do things like guarantee no braces in comments and limit nesting to a specific depth, you could still build an expression to do it. It'll be somewhat messy and hard to maintain, but at least within the realm of the possible.

Problem

Is there any way to match a function block in javascript source code using regular expressions? (Really I'm trying to find the opposite of that, but I figured this would be a good place to start.)

Original source