in reply to Regex Strikes again!
That said here is a sample input file with a few interesting possibilities (yes it compiles):
/** * The HelloWorldApp Class impliments an application that displays "H +ello World!" to standard output */ public class HelloWorldApp { public static void main (String[] args) { // Display "Hello World!" System.out.println("Hello World!"); // end of line comment System.out.println("Hello World!"); /* end of line comment */ System.out.println("Hello World!/*"); /* end of line comment */ /* this is a multi line comment */ /* another comment */ // /* is this a valid comment /* // */ System.out.println("//Hello World!/*"); // is /* this valid } }
Below is some rough code to start grabbing comments. Coding for the cute exceptions is left as an exercise for the student (I hava always wanted to use that line, since it was used on me a long time ago) or as future discussion points. It prints the line number of the file where the comment begins and then the comment.
#!/usr/bin/perl use strict; my $infile = "HelloWorldApp.java"; my %linehash; my $linecounter =0; my $comment_started = 0; my $multiline_comment; open in, "$infile" or die "could not open $infile\n"; while (<in>) { ## you may need to get creative in matching comments ## because java allows some fun combinations - see HelloWorld ## ## grab single line comments first else look for multiline if (/\/\/.*\n/ || /\/\*.*\*\//) { $linehash{$linecounter} = $_; } else { ## possible multiline comment start if ($comment_started) { $multiline_comment = $multiline_comment . $_; ## don't mess with $_ as later comparisons may need the newline in pla +ce chomp $multiline_comment; $multiline_comment = $multiline_comment . " "; ## end of multiline comment if (/\*\//) { $linehash{$comment_started} = $multiline_comment; $comment_started = 0; $multiline_comment = ""; } } ## start multiline comment if (/\/\*/) { $comment_started=$linecounter; } } $linecounter++; } my @keys = sort{$a <=> $b}(keys(%linehash)); for (@keys) { print "key=$_ value=$linehash{$_}"; }
Enjoy
John
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Regex Strikes again!
by nofernandes (Beadle) on Jul 16, 2003 at 14:53 UTC | |
by johndageek (Hermit) on Jul 16, 2003 at 19:42 UTC |