Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

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

by ForgotPasswordAgain (Priest)
on Sep 30, 2007 at 17:53 UTC ( [id://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 \\\' :}'; } }

Replies are listed 'Best First'.
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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://641800]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (5)
As of 2024-03-29 13:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found