http://www.perlmonks.org?node_id=641792


in reply to How do I match/extract a function from a JavaScript file?

Following definitely works in "not so complex" scenarios
#!/usr/bin/perl use strict; my $Jscript = join (" ",<DATA>); # Extract function foo from Jscript my $content = _extract("foo",$Jscript); sub _extract { my ($funct,$Jscript) = @_; my ($round,$curly); $round = qr!\(([^()]*|(??{$round}))*\)!; $curly = qr!\{([^{}]*|(??{$curly}))*\}!; if ($Jscript =~ m!($funct\s*$round\s*$curly)!ms) { print "Matched :\n",$1; } } __DATA__ foo (a, b, c) { if (c) { a++; } else { b--; } print "hi"; } fum (d, e, f, g, h) { if (d) { e++; } else { f = g + h; } print "ho"; }
Output is :
Matched : foo (a, b, c) { if (c) { a++; } else { b--; } print "hi"; }
On more explanation on matching nested parentheses, you can refer Friedl's Mastering Regular Expressions, page 330.