Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: How do I match/extract a function from a JavaScript file?

by ForgotPasswordAgain (Deacon)
on Sep 30, 2007 at 17:53 UTC ( #641800=note: print w/ replies, xml ) Need Help??


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

You need to escape comments and strings, too. Try this one:

bum () { // :} if (d) { e++; } else { f = g + h; } print "ho \" :\}"; /* if (hi) { */ if (ho) { print 'hee \\\' :}'; } }


Comment on Re: How do I match/extract a function from a JavaScript file?
Download Code
Re^2: How do I match/extract a function from a JavaScript file?
by Shakya (Initiate) on Oct 03, 2007 at 17:26 UTC
    ok..here we go with this ..
    #!/usr/bin/perl use strict; use re 'eval'; my $Jscript = join (" ",<DATA>); # Extract function foo from Jscript my $content = _extract("foo",$Jscript); sub _extract { my ($funct,$Jscript) = @_; #regexes to match all but starting positions of strings and commen +ts my $double_quote_str = qr!(\\.|[^"\\])*"!; my $single_quote_str = qr!(\\.|[^'\\])*'!; my $comment1 = qr![^\n\r]*!; my $comment2 = qr!.*?\*/!s; #now match complete strings or comments..whatever matches first wi +ll 'eat' others my $escape_strings = qr! ( '(?{$start='sing_quot'})| "(?{$start='dbl_quot'})| //(?{$start='comment1'})| /\*(?{$start='comment2'}) ) (?(?{$start eq 'sing_quot'})$single_quote_str) (?(?{$start eq 'dbl_quot'})$double_quote_str) (?(?{$start eq 'comment1'})$comment1) (?(?{$start eq 'comment2'})$comment2) !x; my ($round,$curly); # match balanced nested round braces ..escape strings and comments $round = qr! \(( $escape_strings | [^()]|(??{$round}) )* \) !x; # match balanced nested curly braces ..escape strings and comments $curly = qr! { ( $escape_strings | [^{}]|(??{$curly}) )* } !x; if ($Jscript =~ m!(\bfunction\s+$funct\s*$round\s*$curly)!) { print "Matched :\n",$1; } } __DATA__ //.. function foo goes here .......

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://641800]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (6)
As of 2015-07-05 10:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (61 votes), past polls