Jim Pedid
Jim Pedid

Reputation: 2780

Regex for matching whole JavaScript function definitions?

I'm trying to scan through a JavaScript document that has many functions defined throughout it, and to delete a function from the document. I'm hoping that there's a trivial regex trick that I can do here.

Example:

Some JavaScript document:

function wanted_foo(bar) {
  ...
  ...
}
function unwanted_foo(bar) {
  ...
  inner_foo {
     ...
     ...
  }
}
function wanted_foo(bar) {
  ...
  ...
  inner_foo {
     ...
     ...
  }
}

The obvious problem here is that I need to match things of the form "function unwanted_foo(bar) { ... }", except that I only need to match up until the last curly brace of the function, and not to the next curly brace of another function. Is there a simple Regex way of doing this?

Upvotes: 1

Views: 1285

Answers (2)

Omar Awile
Omar Awile

Reputation: 140

One "trick" is to use a counter together with regex.

  • Initialize your counter to 0
  • Match something of the form /^\s*function\s+\w+\(.*\)\s*\{ and when you have found this pattern, remember the position.
  • When you match that pattern, increment your counter
  • Now match { and } separately and increment or decrement your counter depending on what you've found.
  • Keep doing this until your counter is 0 again, then you should have found a function

Hope that's useful to you?

Upvotes: 1

madth3
madth3

Reputation: 7344

Normal regular expressions can't do this because they can't keep count of the previously matched braces and therefore can't find the last one, nonetheless it seems many implementations have capabilities that go beyond normal regex's and Ruby is one of those cases.

Hare are a couple of references about that, although it might not be what you would call simple.

  1. Matching braces in ruby with a character in front
  2. Backreferences

Upvotes: 1

Related Questions