Reputation: 2780
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
Reputation: 140
One "trick" is to use a counter together with regex.
/^\s*function\s+\w+\(.*\)\s*\{
and when you have found this pattern, remember the position.{
and }
separately and increment or decrement your counter depending on what you've found.Hope that's useful to you?
Upvotes: 1
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.
Upvotes: 1