1

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?

1
  • rubular.com is your friend Commented Jul 14, 2012 at 2:49

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the references; I'm trying to approach the problem like this: I have the first { accounted for. I want to search for things like (\{.*\})*, which then should stop at the last }.
1

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?

1 Comment

If I end up doing something like this, would it be better just to work with the String#index method instead of using a Regex? This is probably what I'm going to fall back to, as I can never match the entire function (although I have gotten remarkably close to include everything except the last }; I may also be able to utilize this and just delete the next line, although I worry about test cases that I haven't thought of.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.