2

I was wanting to organize all my javascript functions to put them in alphabetical order a month ago or so and was playing with a regular expression today that made me think of that again. I only want to match the outer functions to avoid nested functions getting moved and almost had it I think, but there is something I am missing.

I used bobble bubble's answer on this page as a starting point. Regular Expression to match outer brackets

function\s.*\(.*\).*\{(?>[^.*\n*]+|(?R))*\}

This will match all function definitions and capture the arguments up to the first curly brace. For some reason I can't get it to match the newlines pattern [^.*\n*]+ while it is part of the expression, but when it is all by itself it matches just fine.

I was using Sublime text editor as my tool to search, but it would end up in a JS file probably as an easy way to manipulate the code.

Community
  • 1
  • 1
Alan
  • 1,730
  • 1
  • 15
  • 32
  • 3
    "to put them in alphabetical order" --- that's a terrible idea, really. The order must be semantic-driven. Anyway, if you want to solve it properly - take any JS syntax parser and it will be 100 times easier and more reliable. – zerkms Mar 23 '17 at 21:55
  • You will have to look for new lines. `\nfunction.*?\n\}` this may be it... – Akxe Mar 23 '17 at 21:59

2 Answers2

5

After a day of fiddling with it, here is a regex that will break up a js file to match all named functions and then break it up into function name, arguments, and body. Unlike Floribon's solution, this will match any formatting style, even minified, and ignores nested braces and functions.

function\s+(?<functionName>\w+)\s*\((?<functionArguments>(?:[^()]+)*)?\s*\)\s*(?<functionBody>{(?:[^{}]+|(?-1))*+})

https://regex101.com/r/sXrHLI/1

Alan
  • 1,730
  • 1
  • 15
  • 32
  • I disagree that it will match any formatting style. Doesn't match function expressions *unless named) and will not match arrow functions to name a few. [Few sample cases](https://regex101.com/r/eWuvYd/1) – VLAZ Nov 01 '19 at 08:09
  • 1
    "The preceding token is not quantifiable" errors are thrown when changing the "Flavor" to Javascript. I wonder if this relates to limitations with Javascripts lookback? – Mark Notton Mar 09 '20 at 09:19
1

This seem to match all functions and their body for me (except the ones defined in one-line, which would require an additional expression)

function.*\(.*\).*\{(.|\n)*?\n\}

Or if you don't want to catch the body just add ?:

function.*\(.*\).*\{(?:.|\n)*?\n\}

The idea is to match until we finish by a new line and a closing curly bracket: this way no bracket (or inner functions) within the body will collide with our search.

floribon
  • 18,567
  • 4
  • 50
  • 66